I noticed a strange behavior between containers in the swing.
To exemplify the test, I created a JFrame and a JPanel, and set the panel as contentPane. I defined the preferred and maximum JPanel size to 400,300. All this can be seen in the example below:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ExcessiveSpacePanelTest {
JFrame frame;
JPanel panel;
public void initGUI(){
frame = new JFrame();
panel = new JPanel();
panel.setBorder(BorderFactory.createLineBorder(Color.RED, 1));
panel.setPreferredSize(new Dimension(400, 300));
panel.setMaximumSize(new Dimension(400, 300));
frame.setContentPane(panel);
frame.pack();
System.out.println("panel size: [" + panel.getSize().width + "," + panel.getSize().height +"]");
System.out.println("frame size: [" + frame.getSize().width + "," + frame.getSize().height+"]");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() ->{
new ExcessiveSpacePanelTest().initGUI();
});
}
}
The result is:
To my surprise, the output at the terminal is:
panel size: [400,300]
frame size: [416,338]
I did not understand why the frame added this extra space, even having nothing in the component that forces the frame to resize.
I tried to set zeroed edges on the panel by adding the row panel.setBorder (BorderFactory.createEmptyBorder(0, 0, 0, 0));
before pack();
but the result is still the same.
The problem with this is that java is giving me a false info, since the panel is scaling in the size of the frame, and from the above result, we have seen that the two are not the same size.
Are the two measures being reported correctly? Why does this occur?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…