问题
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