我有一个封装在 JScrollPane 中的 JTextArea,我用它来记录应用程序的输出。 随着应用程序生成许多行,文本区域中的行数增长得非常快,并且滚动几乎变得不可见。 我想要一个像 Eclipse 控制台一样的文本区域。我的意思是......一个带有垂直滚动的文本区域,但使用滚动时我最多只能显示最新的 200 行。
这是我正在使用的可运行代码:
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import javax.swing.text.DefaultCaret;
public class WindowLog extends JFrame {;
private JPanel contentPane;
private static JTextArea textArea = new JTextArea();
public static void run() {
try {
WindowLog frame = new WindowLog();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void writeText(JTextArea ta, String s){
DefaultCaret caret = (DefaultCaret)ta.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
ta.append(s);
}
/**
* Create the panel.
*/
public WindowLog() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 523, 299);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.setLayout(null);
JLabel lblLog = new JLabel("Log");
lblLog.setBounds(5, 5, 497, 14);
getContentPane().add(lblLog);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(5, 30, 492, 138);
//scrollPane.getViewport().setPreferredSize(new Dimension(300, 100));
textArea.setBorder(BorderFactory.createEmptyBorder(0, 6, 0, 6));
contentPane.add(scrollPane);
scrollPane.setViewportView(textArea);
Main.setTextProva(textArea);
}
}
这是主类:
public class Main {
static JTextArea textProva;
public static void setTextProva(JTextArea textProva) {
Main.textProva = textProva;
}
public static void main(String[] args) {
WindowLog.run();
System.out.println(textProva);
WindowLog.writeText(textProva, "hello"+"\n");
}
提前致谢。
最佳答案
向文本区域的文档添加一个DocumentFilter。在过滤器中检查有多少行。如果达到最大计数,请从文本区域中删除以前的内容。
关于java - 限制 jscrollpane 中显示的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19856238/