如何在按下JButton时将JScrollPane设置为底部?
问题描述:
我有一个面板,其中有一个JScrollPane
和一个JButton
。我想知道如何在按下按钮时将滚动窗格的垂直滚动条设置为底部。如何在按下JButton时将JScrollPane设置为底部?
我曾尝试代码: -
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
writeClient();
jScrollPane2.getVerticalScrollBar().setValue(jScrollPane2.getVerticalScrollBar().getMaximum());
}
但它不会导致极端的底部 - 一个小空间仍然留在底部。
答
我有问题重现您的问题。如果你可以发布所有相关的代码(也可能包括截图),我们可以给你更好的建议。当我运行下面的代码,按下按钮移动滚动窗格一路下跌:
public class ScrollPaneBottom {
public static void main(final String[] args) {
new ScrollPaneBottom().test();
}
private void test() {
final JFrame frame = new JFrame("Move a scroll pane to the bottom");
frame.setBounds(100, 100, 800, 110);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
final String[][] data = {{"One", "Hello"}, {"Une", "Bonjour"},
{"Ein", "Hallo"}, {"Uno", "Hola"}, {"Een", "Hallo"}};
final String[] columnNames = {"Number", "Word"};
final JTable table = new JTable(new DefaultTableModel(data, columnNames));
final JScrollPane scrollPane = new JScrollPane(table);
final JButton button = new JButton("Move to the bottom");
button.addActionListener(e -> {
final int maximum = scrollPane.getVerticalScrollBar().getMaximum();
scrollPane.getVerticalScrollBar().setValue(maximum);
});
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.getContentPane().add(button, BorderLayout.SOUTH);
frame.setVisible(true);
}
}
1)为了更好地帮助越早,张贴[MCVE(http://stackoverflow.com/help/mcve) (最小完整可验证示例)或[SSCCE](http://www.sscce.org/)(简短,独立,正确的示例)。 2)以小写字母输入的单词难以阅读,比如试图听别人嘟someone。请在句子的开头使用大写字母,单词I以及诸如'ArrayList'或Oracle的专有名称。 – 2014-11-23 11:34:14