开发者

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

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 app开发者_如何学Goear right? Well it stays the same 600px tall how I set it at the start.


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.


All you need to do is call revalidate() on the content within the JScollPane after updating it's size. Also, use the setPreferredSize() when using a layout manager.

public void setScale(int value) {
     setPreferredSize(new Dimension(1000, 1000);   
     revalidate();
}

That will force the JScrollPane to update it's scrollbars.

Also, you could call

paintCanvas.revalidate()

If you wanted to update the JScrollPane from outside of your paintCanvas class

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜