要创建一个不可编辑的自动滚动的JTextArea,你可以使用JScrollPane来包装JTextArea,并设置JTextArea为不可编辑。然后使用setCaretPosition方法将滚动条滚动到文本的末尾。
以下是一个示例代码:
import javax.swing.*;
import java.awt.*;
public class AutoScrollingTextAreaExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Auto Scrolling JTextArea Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
JTextArea textArea = new JTextArea();
textArea.setEditable(false); // 设置为不可编辑
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
// 添加一些文本到JTextArea
for (int i = 0; i < 100; i++) {
textArea.append("Line " + i + "\n");
}
// 将滚动条滚动到文本的末尾
textArea.setCaretPosition(textArea.getDocument().getLength());
frame.setVisible(true);
}
}
这个示例代码创建了一个带有滚动条的JTextArea,并设置JTextArea为不可编辑。然后通过循环向JTextArea添加一些文本。最后,使用setCaretPosition方法将滚动条滚动到文本的末尾,以实现自动滚动效果。
下一篇:不可变结构体的值正在发生变化