如何修改 JScrollPane 内 JPanel 的大小?
我就是搞不明白。我有一个滑块来增加 JPanel 的大小(用作画布来绘图)。
每当 JPanel 接收到事件时,我都会使用 setBounds() 调整它的大小,并且我可以看到它在瞬间调整大小,但下一个 Paint 或其他操作会将其切换回滑块的首选大小属性给出的原始大小。
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);
}
}
因此,当我尝试将 JPanel 的大小更改为大值时,它应该调整大小并且滚动条应该显示正确吗?好吧,它的高度与我一开始设置的一样 600px。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用布局管理器时切勿使用 setSize() 或 setBounds。重要的是“首选尺寸”。通常,组件的首选尺寸由布局管理器自动确定。但如果您要在面板上进行自定义绘画,您可能需要手动确定首选尺寸。
当面板的首选尺寸大于滚动窗格的尺寸时,将出现滚动条。重写 getPreferredSize() 方法(首选解决方案)或使用自定义面板的 setPreferredSize() 方法。
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.
您需要做的就是在更新 JCollPane 的大小后对其内容调用 revalidate() 。另外,在使用布局管理器时使用 setPreferredSize()。
这将强制 JScrollPane 更新其滚动条。
您可以调用
另外,如果您想从paintCanvas类之外更新JScrollPane,
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.
That will force the JScrollPane to update it's scrollbars.
Also, you could call
If you wanted to update the JScrollPane from outside of your paintCanvas class