将JDialog显示为工作表不起作用

问题描述 投票:11回答:3

我目前正在使用此代码创建JDialog;

package com.kamuara.reposync.window;

import java.awt.Dialog;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;

public class SheetDialog {

    private JFrame _windowFrame;

    public static void main(String[] args) {
        System.setProperty("apple.awt.documentModalSheet", "true");
        System.setProperty("apple.awt.brushMetalLook", "true");

        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            new SheetDialog();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public SheetDialog() {
        _windowFrame = new JFrame();
        _windowFrame.setResizable(false);
        _windowFrame.setBounds(100, 100, 451, 320);
        _windowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        _windowFrame.getContentPane().setLayout(null);
        _windowFrame.setVisible(true);

        JButton showDialogButton = new JButton("Show Dialog");
        showDialogButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showSheetDialog(_windowFrame, "Test", "This should be a sheet dialog", "Oke");
            }
        });
        showDialogButton.setBounds(328, 263, 117, 29);
        _windowFrame.getContentPane().add(showDialogButton);
    }

    public void showSheetDialog(JFrame owner, String title, String message, String button) {
        final JDialog messageDialog = new JDialog(owner, title, Dialog.ModalityType.DOCUMENT_MODAL);
        messageDialog.setBounds(30, 0, owner.getWidth() - 60, 130);

        // TODO: only when os is osx
        messageDialog.getRootPane().putClientProperty("apple.awt.documentModalSheet", "true");
        messageDialog.setLayout(null);

        int offsetX = 25;

        JLabel titleLabel = new JLabel(title);
        titleLabel.setFont(new Font("Lucida Grande", Font.BOLD, 13));
        titleLabel.setBounds(offsetX, 10, 100, 25);
        messageDialog.getContentPane().add(titleLabel);

        JLabel messageLabel = new JLabel(message);
        messageLabel.setVerticalTextPosition(JLabel.TOP);
        messageLabel.setHorizontalTextPosition(JLabel.LEFT);
        messageLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
        messageLabel.setBounds(offsetX, 10, messageDialog.getWidth() - 10, messageDialog.getHeight() - 60);
        messageDialog.getContentPane().add(messageLabel);

        JButton okButton = new JButton(button);
        okButton.setBounds(messageDialog.getWidth() - 105, messageDialog.getHeight() - 35, 100, 25);
        okButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                messageDialog.dispose();
            }
        });
        messageDialog.getContentPane().add(okButton);

        messageDialog.setVisible(true);
    }
}

我以前使用Java 6来编译应用程序并设置clientProperty apple.awt.documentModalSheet可以完美地在OSX上将对话框显示为“ Sheet”,但现在我开始使用Java 7(更新25),并且不再使用该对话框显示为表格。我似乎找不到任何更新文档。他们对此有什么改变吗?我该如何解决?使用工作表,当前的界面设计要好于对话框。

更新

我发现了以下错误报告,似乎与我遇到的问题相同;

http://bugs.sun.com/view_bug.do?bug_id=8010197

有人知道如何解决此问题吗?我已经研究了QuaQua之类的库,但是我不希望使用任何库,因为我只想要工作表功能。

更新2

我尝试过QuaQua,但是使用Java 7编译时,库当前存在完全相同的问题。任何解决方法?

更新3

用工作示例替换的代码(http://pastebin.com/PJ8VGdPb

更新4

[发现SWT的Shell类具有一种名为SWT.SHEET的样式,该样式仍可在Java7中使用,我不喜欢使用SWT之类的库,但这似乎是唯一的解决方案。

java macos swing jdialog
3个回答
2
投票

据我所知,Apple尚未正式发布其JDK 7版本。Apple已为其OS X优化的最新JDK版本仍为JDK6。这也是Java的更新来自AppStore更新的原因。标签。这些更新并非直接来自Oracle。

如果直接从Oracle下载JDK 7,这是一个更通用的,未经调整的版本。

所以,我认为您只需要等待苹果发布其OS X优化的JDK 7。

从Oracle下载时,我经历了许多OS X功能无法正常工作:

  • 触控板手势
  • 即使尝试通过UIManager手动设置,Native Aqua Look'n'Feel也不起作用。
  • 使用JOptionPane时应用程序图标不起作用。
  • JMenu会粘在JFrame本身中,而不是移到屏幕顶部。

2
投票

似乎在JDK修复bug之前,您必须自己实现Sheet。

关键点是:

  1. 使用窗框的玻璃窗格来容纳图纸对话框
  2. 使用GridBagLayout(带有NORTH锚点)将对话框置于窗格的顶部|中心
  3. 在显示/消失时,通过重复绘制对话框,每次绘制对话框的更多/更少部分,使工作表动画化

以下为示例代码

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;

import javax.swing.Box;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.LineBorder;

public class SheetableJFrame extends JFrame implements ActionListener {

    public static final int INCOMING = 1;
    public static final int OUTGOING = -1;
    public static final float ANIMATION_DURATION = 1000f;
    public static final int ANIMATION_SLEEP = 50;

    JComponent sheet;
    JPanel glass;
    Sheet animatingSheet;
    boolean animating;
    int animationDirection;
    Timer animationTimer;
    long animationStart;
    BufferedImage offscreenImage;

    public SheetableJFrame() {
        super();
        glass = (JPanel) getGlassPane();
        glass.setLayout(new GridBagLayout());
        animatingSheet = new Sheet();
        animatingSheet.setBorder(new LineBorder(Color.black, 1));
    }

    public JComponent showJDialogAsSheet(JDialog dialog) {
        sheet = (JComponent) dialog.getContentPane();
        sheet.setBorder(new LineBorder(Color.black, 1));
        glass.removeAll();
        animationDirection = INCOMING;
        startAnimation();
        return sheet;
    }

    public void hideSheet() {
        animationDirection = OUTGOING;
        startAnimation();
    }

    private void startAnimation() {
        glass.repaint();
        // clear glasspane and set up animatingSheet
        animatingSheet.setSource(sheet);
        glass.removeAll();
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.NORTH;
        glass.add(animatingSheet, gbc);
        gbc.gridy = 1;
        gbc.weighty = Integer.MAX_VALUE;
        glass.add(Box.createGlue(), gbc);
        glass.setVisible(true);

        // start animation timer
        animationStart = System.currentTimeMillis();
        if (animationTimer == null) animationTimer = new Timer(ANIMATION_SLEEP, this);
        animating = true;
        animationTimer.start();
    }

    private void stopAnimation() {
        animationTimer.stop();
        animating = false;
    }

    // used by the Timer
    public void actionPerformed(ActionEvent e) {
        if (animating) {
            // calculate height to show
            float animationPercent = (System.currentTimeMillis() - animationStart) / ANIMATION_DURATION;
            animationPercent = Math.min(1.0f, animationPercent);
            int animatingHeight = 0;

            if (animationDirection == INCOMING) {
                animatingHeight = (int) (animationPercent * sheet.getHeight());
            } else {
                animatingHeight = (int) ((1.0f - animationPercent) * sheet.getHeight());
            }
            // clip off that much from sheet and put it into animatingSheet
            animatingSheet.setAnimatingHeight(animatingHeight);
            animatingSheet.repaint();

            if (animationPercent >= 1.0f) {
                stopAnimation();
                if (animationDirection == INCOMING) {
                    finishShowingSheet();
                } else {
                    glass.removeAll();
                    glass.setVisible(false);
                    glass.setLayout(new GridBagLayout());
                    animatingSheet = new Sheet();
                }
            }
        }
    }

    private void finishShowingSheet() {
        glass.removeAll();
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.NORTH;
        glass.add(sheet, gbc);
        gbc.gridy = 1;
        gbc.weighty = Integer.MAX_VALUE;
        glass.add(Box.createGlue(), gbc);
        glass.revalidate();
        glass.repaint();
    }

    class Sheet extends JPanel {
        Dimension animatingSize = new Dimension(0, 1);
        JComponent source;
        BufferedImage offscreenImage;

        public Sheet() {
            super();
            setOpaque(true);
        }

        public void setSource(JComponent source) {
            this.source = source;
            animatingSize.width = source.getWidth();
            makeOffscreenImage(source);
        }

        public void setAnimatingHeight(int height) {
            animatingSize.height = height;
            setSize(animatingSize);
        }

        private void makeOffscreenImage(JComponent source) {
            GraphicsConfiguration gfxConfig = GraphicsEnvironment.getLocalGraphicsEnvironment()
                    .getDefaultScreenDevice().getDefaultConfiguration();
            offscreenImage = gfxConfig.createCompatibleImage(source.getWidth(), source.getHeight());
            Graphics2D offscreenGraphics = (Graphics2D) offscreenImage.getGraphics();
            source.paint(offscreenGraphics);
        }

        public Dimension getPreferredSize() {
            return animatingSize;
        }

        public Dimension getMinimumSize() {
            return animatingSize;
        }

        public Dimension getMaximumSize() {
            return animatingSize;
        }

        public void paint(Graphics g) {
            // get the bottom-most n pixels of source and paint them into g, where n is height
            BufferedImage fragment = offscreenImage.getSubimage(0, offscreenImage.getHeight() - animatingSize.height,
                    source.getWidth(), animatingSize.height);
            g.drawImage(fragment, 0, 0, this);
        }
    }
}

测试代码

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JDialog;
import javax.swing.JOptionPane;

public class SheetTest extends Object implements PropertyChangeListener {

    JOptionPane optionPane;
    SheetableJFrame frame;

    public static void main(String[] args) {
        new SheetTest();
    }

    public SheetTest() {
        frame = new SheetableJFrame();
        // build JOptionPane dialog and hold onto it
        optionPane = new JOptionPane("Do you want to close?", JOptionPane.QUESTION_MESSAGE, JOptionPane.CANCEL_OPTION);
        frame.setSize(640, 480);
        frame.setVisible(true);
        optionPane.addPropertyChangeListener(this);

        JDialog dialog = optionPane.createDialog(frame, "irrelevant");
        frame.showJDialogAsSheet(dialog);
    }

    public void propertyChange(PropertyChangeEvent pce) {
        if (pce.getPropertyName().equals(JOptionPane.VALUE_PROPERTY)) {
            System.out.println("Selected option " + pce.getNewValue());
            frame.hideSheet();
        }
    }
}

参考http://oreilly.com/pub/h/4852http://book.javanb.com/swing-hacks/swinghacks-chp-6-sect-6.html


0
投票

这是我想到的一个超级狡猾的骇客,它设置了JDK现在似乎忘记设置并手动将窗口放置在正确位置的标志。虽然仍然缺少阴影,所以我想知道是否有人可以对此进行改进。 ;)

这与内部类和私有字段混淆,因此它可能会在任何给定的JDK新发行版中中断,但仍适用于8u5。也许它将为这些内部AWT类的结构提供一些见识。

public static void makeSheet(Dialog dialog) {
    dialog.addNotify();
    ComponentPeer peer = dialog.getPeer();

    // File dialogs are CFileDialog instead. Unfortunately this means this hack
    // can't work for those. :(
    if (peer instanceof LWWindowPeer) {
        LWWindowPeer windowPeer = (LWWindowPeer) dialog.getPeer();
        //XXX: Should check this before casting too.
        CPlatformWindow platformWindow = (CPlatformWindow) windowPeer.getPlatformWindow();
        try {
            Method method = CPlatformWindow.class.getDeclaredMethod(
                "setStyleBits", int.class, boolean.class);
            method.setAccessible(true);
            method.invoke(platformWindow, 64 /* CPlatformWindow.SHEET */, true);

            Window parent = dialog.getOwner();
            dialog.setLocation(dialog.getLocation().x,
                               parent.getLocation().y + parent.getInsets().top);
        } catch (Exception e) {
            Logger.getLogger(SheetHack.class.getName())
                .log(Level.WARNING, "Couldn't call setStyleBits", e);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.