4
I noticed a strange behavior between containers in the swing.
To illustrate the test, I created a JFrame
and a JPanel
, and defined the panel as contentPane of JFrame
. Set the preferred and maximum size of the JPanel
as 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 of the screen is:
To my surprise, the exit at the terminal is:
panel size: [400,300]
frame size: [416,338]
I don’t understand why the frame added this extra space, even though it has nothing in the component that forces the frame to resize.
I tried to set zeroed edges on the panel by adding the line panel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
before the pack()
but still the result is the same.
The problem with this is that java is giving me a false information, since the panel is sizing in the frame size, and by the result above, we saw that the two do not have the same size.
Are the two measurements being correctly informed? Why does this occur?
But then you set the frame size, which forces the layoutmanager to reduce the internal size of the components. The problem with this behavior is that Jpanel has one size, but in the image we see another (its width is not 400 but 416)
– user28595
Whose width? My frame?
– Jéf Bueno
Yes, the output shows a 16px difference (which is no small thing) but in the image the panel has the same width as the frame. This makes me a problem, because I work with the panel size, but the defined size(400) is not the displayed size(416)
– user28595