我有一个带有JTextAreas作为组件的JTabbedPane。使用另一种方法我将Texts添加到TextAreas。但是如果TextArea已满,它不会向下滚动,所以我看不到最新的文本。我该如何解决这个问题?
public class View extends JFrame{
public class Field extends JTextArea{
public Field(){
this.setEditable(false);
this.setLineWrap(true);
DefaultCaret caret = (DefaultCaret)this.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
}
}
public View(){
this.setLayout(new BorderLayout());
this.tabs = new JTabbedPane();
this.tabs.add("abc", new Field());
this.add(tabs, BorderLayout.CENTER);
}
}
答案 0 :(得分:2)
您需要将JTextArea
置于JScrollPane
内以使其可滚动:
import javax.swing.*;
import javax.swing.text.DefaultCaret;
import java.awt.*;
public class Example {
public static void main(String[] args) {
JFrame jFrame = new JFrame();
JTextArea textArea = new JTextArea();
DefaultCaret caret = (DefaultCaret)textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JScrollPane jScrollPane = new JScrollPane(textArea);
jScrollPane.setPreferredSize(new Dimension(300, 300));
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("abc", jScrollPane);
jFrame.setContentPane(tabbedPane);
jFrame.pack();
jFrame.setVisible(true);
for(int i = 0; i < 100; i ++) {
textArea.append(i + "\n");
}
}
}