WonderCsabo
WonderCsabo

Reputation: 12207

resizing from paintComponent method

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?

Upvotes: 2

Views: 873

Answers (2)

tenorsax
tenorsax

Reputation: 21223

When pack() is executed the panel is still invisible and its paintComponent() was not executed and as a result setPreferredSize() wasnt executed as well.

But don't call setPreferredSize from paintComponent(). Do your painting in paintComponent nothing 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 before pack().

Also see Should I avoid the use of set[Preferred|Maximum|Minimum]Size methods in Java Swing.

Upvotes: 4

martinez314
martinez314

Reputation: 12332

    public MyPanel() {
        setPreferredSize(new Dimension(640, 480));
    }

Upvotes: 2

Related Questions