Resizing JPanel on OS X

人走茶凉 提交于 2019-12-02 07:48:37
trashgod

The following complete example does not freeze when the dialog is resized or maximized. Here are a few things to note:

  • The default layout of a JPanel is FlowLayout; for comparison, I've set the frame's layout the same.

  • Invoking pack() "Causes this Window to be sized to fit the preferred size and layouts of its subcomponents." Since the dialog contains only an empty Jpanel, I've overridden getPreferredSize() to show the effect.

  • Swing GUI objects should be constructed and manipulated only on the event dispatch thread.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 * @see https://stackoverflow.com/a/22450263/230513
 */
public class Test {

    private void display() {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());
        frame.add(new JLabel("Frame"));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        JDialog dialog = new JDialog(frame, true);
        final JPanel panel = new JPanel(){

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(320, 240);
            }
        };
        panel.add(new JLabel("Dialog"));
        panel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 14));
        dialog.add(panel);
        dialog.pack();
        dialog.setLocationRelativeTo(frame);
        dialog.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Test().display();
            }
        });
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!