Java - Setting position of jScrollBar

心不动则不痛 提交于 2019-12-13 01:25:55

问题


I have a JTable in a JScrollPane, and the table gets new rows of data every once in a while. Eventually there are more rows of data than can be displayed at once and so the ScrollPane kicks in. I want the Scroll Pane to jump to the bottom (to its maximum value) every time new data is added, so I wrote this, which is called right after the new row is added:

jScrollPane1.getVerticalScrollBar().setValue(jScrollPane1.getVerticalScrollBar().getMaximum());

It works quite well, but there is a problem- It doesn't scroll to the complete bottom. It always leaves out one row of the table that you need to manually scroll down to reach the complete bottom.

My suspicion is that the new row of data is somehow added only after the method is over (it is activated after pressing a JButton and activating an actionPerformed kind of method).

How to fix this?


回答1:


you need to queue it at the end of current processing events using SwingUtilities.invokeLater; it would look like this:

SwingUtilities.invokeLater(new Runnable() {
  public void run() {
   jScrollPane1.getVerticalScrollBar().setValue(jScrollPane1.getVerticalScrollBar().getMaximum());
  }
 }
);

otherwise will run during the current event and will happen before any actual update.

remember to make them variable final to pass them into an anonymous inner class



来源:https://stackoverflow.com/questions/24064653/java-setting-position-of-jscrollbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!