Resizing JPanel on OS X

前端 未结 1 1604
攒了一身酷
攒了一身酷 2021-01-27 13:52

I have two Swing components: JDialog -> JPanel

I want to fill all space in the JDialog with the JPanel. Default settings work fine. I can change size of the dialog and

相关标签:
1条回答
  • 2021-01-27 14:21

    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.

    image

    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();
                }
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题