简体   繁体   中英

Java - Setting position of jScrollBar

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM