How to modify a JPanel's size inside a JScrollPane?

sekmet64 picture sekmet64 · Nov 16, 2010 · Viewed 8.9k times · Source

I just can't get this right. I have a slider to increase my JPanel's size (used as a canvas to draw on).

Whenever the JPanel receives the event, I resize it with setBounds() and I can see it resizing for a split second, but a next Paint or something switches it back to the original size given by the slider's preferred size property.

public class ShapesMainFrame extends JFrame {
    private PaintCanvas paintCanvas;
    public ShapesMainFrame() {
        [...]
        JScrollPane scrollPane = new JScrollPane(paintCanvas);
        scrollPane.setPreferredSize(new Dimension(1,600));
        add(scrollPane, BorderLayout.CENTER);
        pack();
    }
}

public class PaintCanvas extends JPanel {
    [...]
    public void setScale(int value) {
        setSize(1000,1000);
    }
}

So when I try to change the size of the JPanel to a big value it should resize and the scrollbars should appear right? Well it stays the same 600px tall how I set it at the start.

Answer

camickr picture camickr · Nov 17, 2010

Never use setSize() or setBounds when using a layout manager. Its the "preferred size" that is important. Normally the preferred size of a component is determined automatically by the layout manager. But if you are doing custom painting on the panel you may need to determine the preferred size manually.

The scrollbars will appear when the preferred size of the panel is greater than the size of the scroll pane. Override the getPreferredSize() method (preferred solution) or use the setPreferredSize() method of the custom panel.