I have this little code
public class Test extends JFrame {
public static void main(String[] args) {
new Test();
}
Test() {
getContentPane().add(new MyPanel());
pack();
setVisible(true);
}
private class MyPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
setSize(640, 480);
setPreferredSize(new Dimension(640, 480));
setMinimumSize(new Dimension(640, 480));
g.fillRect(20, 20, 50, 50);
}
}
Unfortunately the frame is not resized to the size of the nested panel after calling pack(). I already read the related answers for this topic, but none of them helped. Could you provide me a solution, please?
When
pack()is executed the panel is still invisible and itspaintComponent()was not executed and as a resultsetPreferredSize()wasnt executed as well.But don’t call
setPreferredSizefrompaintComponent(). Do your painting inpaintComponentnothing else. Avoid putting program logic into that method. Painting operations should be fast and optimized for better performance and user experience. See Performing Custom Painting for more details.Override panel’s
getPrefferedSize(), or at least execute setPrefferedSize beforepack().Also see Should I avoid the use of set[Preferred|Maximum|Minimum]Size methods in Java Swing.