如何在Java Swing中自动滚动到底部 [英] How to auto scroll to bottom in Java Swing

查看:491
本文介绍了如何在Java Swing中自动滚动到底部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有JScrollPane(根据需要带有垂直滚动条)的简单JPanel.

I have a simple JPanel with a JScrollPane (with vertical scrollbar as needed) on it.

事物被添加到JPanel(或从中删除),并且当它超出面板的底部时,我希望JScrollPane根据需要自动向下滚动到底部,或者如果某些组件离开面板,则向上滚动.

Things get added to (or removed from) the JPanel and when it goes beyond the bottom of the panel, I want the JScrollPane to scroll down to the bottom automatically as needed or scroll up if some components go away from the panel.

我该怎么做?我想我需要某种侦听器,只要JPanel高度发生变化,该侦听器就会被调用?还是有像JScrollPanel.setAutoScroll(true)这样简单的东西?

How shall I do this? I am guessing I need some kind of listener which gets called whenever the JPanel height changes? Or is there something as simple as JScrollPanel.setAutoScroll(true)?

推荐答案

为面板添加/删除组件时,应在面板上调用revalidate(),以确保组件的布局正确.

When you add/remove components for a panel you should invoke revalidate() on the panel to make sure the components are laid out properly.

然后,如果要滚动到底部,则应该可以使用:

Then, if you want to scroll to the bottom then you should be able to use:

JScrollBar sb = scrollPane.getVerticalScrollBar();
sb.setValue( sb.getMaximum() );

这篇关于如何在Java Swing中自动滚动到底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆