[英]JList with ScrollPane auto-scroll bug
I have a JList with a ScrollPane. 我有一个带有ScrollPane的JList。 When i press a button, a new line is added to the JList.But the problem is that it doesn't scroll to the last element, but the second last element. 当我按下按钮时,新行会添加到JList。但是问题是它不会滚动到最后一个元素,而是倒数第二个元素。 Here is a portion of code used : There are no erros. 这是一部分使用的代码:没有错误。 Everything works good except this . 除此之外,一切都很好。
DefaultListModel<String> model = new DefaultListModel<String>();
JList<String> list = new JList<String>(model);
JPanel panel = new JPanel(new GridLayout(0,1));
panel.add(list);
scroll = new JScrollPane(panel);
JPanel p = new JPanel(new BorderLayout());
p.add(scroll, BorderLayout.CENTER);
p.add(buttonPanel, BorderLayout.SOUTH); // here are more button's including the one with the action described below
public void actionPerformed(ActionEvent e) {
list.setFont(new Font("Times new Roman", Font.PLAIN, 30));
model.add(list.getModel().getSize(), "Some text randomly"+ i++);
panel.repaint();panel.revalidate();
scroll.getVerticalScrollBar().setValue(scroll.getVerticalScrollBar().getMaximum());
}
I think that the actual repainting happens after this method has ended. 我认为实际的重新绘制是在此方法结束后发生的。 Try calling the last line using SwingUtilities.invokeLater()
like this: 尝试使用SwingUtilities.invokeLater()
调用最后一行,如下所示:
SwingUtilities.invokeLater(new Runnable() { public void run() {
scroll.getVerticalScrollBar().setValue(scroll.getVerticalScrollBar().getMaximum());
}
});
Beware while copy-pasting this into your IDE: There is a hidden character (zero-width non-joiner) in the HTML that is not allowed in your Java code. 将其复制粘贴到IDE时要当心:HTML中有一个隐藏字符(零宽度非连接符),Java代码中不允许使用该字符。 Just remove everything between the braces after getMaximum()
. 只需删除getMaximum()
之后大括号之间的所有内容即可。
(In Java 8 you can use a Lambda expression to make this statement smaller and better readable.) (在Java 8中,您可以使用Lambda表达式使该语句更小并且更易于阅读。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.