我正在开发一个保存计算运行日志的小型计算器小部件。每次添加新条目时,都应该滚动到日志的底部。这部分似乎工作正常。 问题是,当我按下不添加到日志的计算器按钮时,日志窗格始终滚动回顶部,滚动条消失。我怎么能阻止它做到这一点?为什么我的Java Swing JScrollPane继续滚动到顶部?
,增加了日志的代码是:
private JTextPane logArea; //This is placed inside a JScrollPane
private void log(String m, SimpleAttributeSet a) {
int len = logArea.getDocument().getLength();
logArea.setEditable(true);
logArea.setCaretPosition(len);
logArea.setCharacterAttributes(a, false);
logArea.replaceSelection(m);
logArea.scrollRectToVisible(new Rectangle(0,logArea.getBounds(null).height,1,1));
logArea.setEditable(false);
}
,这似乎与滚动搞乱的代码是:
private void addDigit(char digit) {
if (clearDisplayBeforeDigit) {
clearNumDisplay();
}
if (numInDisplay.getText().length() < maxNumDigits) {
if (digit == '.') { //Point
if (!hasPoint) { //Only one point allowed
hasPoint = true;
String newText = numInDisplay.getText() + ".";
numInDisplay.setText(newText);
}
} else { //New digit
String newText = numInDisplay.getText() + digit;
numInDisplay.setText(newText);
}
}
}
为了尽快提供更好的帮助,请发布[SSCCE](http://sscce.org/)。 – 2012-02-12 04:03:02
从哪里调用'log'?您也可以考虑使用'JScrollPane'的'JScrollBar'滚动到底部。 ([链接](http://stackoverflow.com/a/5150437/758280),我不知道这是否会解决您的问题,但它不能伤害尝试。) – Jeffrey 2012-02-12 04:06:37