【发布时间】:2015-03-24 12:32:08
【问题描述】:
我正在尝试创建一个JTextArea,每次将文本附加到该文本区域时,它都会滚动到底部。否则,用户应该能够滚动顶部并查看上一条消息。我使用了这段代码:
JTextArea terminalText = new JTextArea();
JPanel terminal = new JPanel();
terminal.setLayout(new BorderLayout());
add(terminal); //Adds the terminal to mother JPanel
//I added scrollbar to my JTextArea
JScrollPane scroll = new JScrollPane(terminalText);
terminal.add(scroll, BorderLayout.CENTER);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
e.getAdjustable().setValue(e.getAdjustable().getMaximum());
}});
到目前为止,每次我使用terminalText.append 将某些内容附加到terminalText 时,这段代码似乎都会让我的文本区域滚动到terminalText 文本区域的底部。
但是,用户不能使用滚动条滚动到顶部以查看上一条消息。有没有办法来解决这个问题?我应该使用DocumentListener 来实现这一点吗?
【问题讨论】:
-
每次附加一些文本时使用
setCaretPosition(terminalText.getDocument().getLength());之类的东西。您可以将其放在DoucmentListener中,但可能需要使用SwingUtilities#invokeLater以避免可能的突变问题 -
我在我的 GUI 中多次使用 append,我希望能够自动化这个过程。你能解释一下
SwingUtilities#invokeLater和DocumentListener的用法吗?
标签: java swing awt jscrollpane jtextarea