简体   繁体   中英

Force JTextArea to the bottom of JScrollPane

I've got the following code:

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");
}
}

The code results in the following JScrollPane:

JScrollPane的

How do I force the JTextArea to the bottom of the JScrollPane so it looks like this (NB I use MigLayout):

JScrollPane2

一种方法是根据JTextArea的行数在开头添加空白行,并使用setCaretPosition()方法将插入号位置设置为TextArea的末尾。

To force JTextArea at the end of JScrollPane , you can make use of Layouts. BorderLayout will do the job for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM