当形状位于 JPanel 外部时自动滚动
我有一个 JPanel,可以在其中绘制形状。该面板被添加到scrollPane 中。但当形状不在场景中时,滚动不起作用。有没有一种简单的方法可以自动滚动,或者我必须以编程方式进行。
谢谢
I have a JPanel where I draw shapes. this panel is added to a scrollPane. but the scrolling doesn't work when a shape is out of the scene. is there an easy way to autoscroll or I have to do it programmatically.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设您使用 JPanel 作为自定义绘图的画布(即您没有向其中添加任何 JComponent)。如果是这种情况,JScrollPane 无法知道 JPanel 有多大,并且只会调整其大小以精确填充scrollPane 的视口(这意味着您永远不会真正获得滚动条)。
要解决此问题,您应该覆盖 JPanel 上的 getPreferredSize。
编辑:
此外,由于您正在进行自定义绘制,因此请确保每当您要绘制的形状发生变化时都调用重新验证。这告诉 swing 它需要重新考虑 JPanel 的布局/大小。
I'm assuming you're using the JPanel as a canvas for custom drawing(i.e. you're not adding any JComponents to it). If that's case, the JScrollPane has no way of knowing how large the JPanel is and will just size it to exactly fill the scrollPane's viewport(which means you'll never actually get scroll bars).
To fix this issue you should override getPreferredSize on your JPanel.
Edit:
Also, since you're doing custom drawing make sure to call revalidate whenever the shapes you want to draw change. This tells swing that it needs to re-think the layout/size of the JPanel.