强制JTextArea到JScrollPane的底部

时间:2014-03-01 18:09:41

标签: java swing jscrollpane jtextarea

我有以下代码:

public class LobbyView extends JPanel
{
    this.setLayout(new MigLayout());
    private final JTextArea chatWindowMessage = new JTextArea();
    private final JScrollPane chatWindow = new JScrollPane(chatWindowMessage);

LobbyView(Window sentWindow)
{
    chatWindow.setViewportView(chatWindowMessage);
    chatWindow.setPreferredSize(new Dimension(300, 300));
    chatWindow.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

    chatWindowMessage.setLineWrap(true);
    chatWindowMessage.append("test" + "\n");
    chatWindowMessage.append("test 2" + "\n");

    this.add(chatWindow, "pos 180px 75px");
    this.add(chatMessage, "pos 180px 380px");
}
}

代码导致以下JScrollPane:

JScrollPane

如何强制JTextArea到JScrollPane的底部,看起来像这样(N.B。我使用MigLayout):

JScrollPane2

2 个答案:

答案 0 :(得分:0)

一种方法是在开头添加空白行,具体取决于JTextArea的行数,并使用setCaretPosition()方法将插入符号位置设置为JTextArea的末尾。

答案 1 :(得分:0)

要在JTextArea的末尾强制JScrollPane,您可以使用布局。 BorderLayout将为您完成这项工作。