Get the real size of a JFrame content

前端 未结 2 1995
既然无缘
既然无缘 2021-01-12 01:28

I get a JFrame and i want to display a JLabel with a border in it with a padding of maybe 50px. When i set the size of the JFrame to 750, 750, and the size of the JLabel to

2条回答
  •  佛祖请我去吃肉
    2021-01-12 01:46

    Using setPreferredSize() is problematic, as it always overrules the component's calculation with an arbitrary choice. Instead, pack() the enclosing Window to accommodate the preferred sized of the components, as shown below.

    image

    import java.awt.Color;
    import java.awt.EventQueue;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.border.Border;
    import javax.swing.border.CompoundBorder;
    
    /**
     * @see https://stackoverflow.com/a/13481075/230513
     */
    public class NewGUI extends JPanel {
    
        private static final int S1 = 10;
        private static final int S2 = 50;
        private JLabel label = new JLabel("Hello, world!");
    
        public NewGUI() {
            label.setHorizontalAlignment(JLabel.CENTER);
            Border inner = BorderFactory.createEmptyBorder(S1, S1, S1, S1);
            Border outer = BorderFactory.createLineBorder(Color.black);
            label.setBorder(new CompoundBorder(outer, inner));
            this.setBorder(BorderFactory.createEmptyBorder(S2, S2, S2, S2));
            this.add(label);
        }
    
        private void display() {
            JFrame f = new JFrame("NewGUI");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(this);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    new NewGUI().display();
                }
            });
        }
    }
    

提交回复
热议问题