如何将文本添加到JTextArea? (控制台模拟)

如何在JTextArea中添加文本/命令(如在控制台中)?

或者,更具体地说,如何在我的FTP程序中添加JTextArea作为控制台并添加C:\ tmp \ -list之类的命令以及之前添加的不可编辑文本?

当然有可能。 您可以使用JTextArea.append(String)方法:

JTextArea textArea = new JTextArea(); textArea.append("Your new String"); 

来自JavaDoc:

将给定文本附加到文档的末尾。

小心你必须自己添加换行符

 textArea.append("Your new String\n"); 

如果你想在最后添加一个新行。


如果您想拥有一个真正的自制控制台,请查看Lanterna或JLine的示例 。

这是一个非常不完整的答案,但它是一个开始。 此代码适用于扩展javax.swing.JFrame的Test.java。 它构建一个简单的GUI,创建一个新的PrintStream和OutputStream(它覆盖write(int b)以将一个字符附加到JTextArea),使用System.setOut(PrintStream),然后使用System.out.println(String)来测试它。

 import java.io.PrintStream; import java.io.OutputStream; import javax.swing.JFrame; import javax.swing.JTextArea; /** * * @author caucow */ public class Test extends JFrame { PrintStream printOut; OutputStream out; JPanel container; JTextArea example; public static void main(String[] args) { Test test = new Test(); test.setVisible(true); } public Test() { setSize(500, 500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create the JTextArea with some default text. example = new JTextArea("//There is some text here\n"); example.setBounds(0, 0, 500, 500); add(example); // Create the OutputStream which will be written to when using System.out out = new OutputStream() { @Override // Override the write(int) method to append the character to the JTextArea public void write(int b) throws IOException { example.append("" + (char) b); } }; // Create the PrintStream that System.out will be set to. // Make sure autoflush is true. printOut = new PrintStream(out, true); // Set the system output to the PrintStream System.setOut(printOut); // Test it out System.out.println("\nTest Output"); System.out.println(); System.out.println("More testing."); System.out.println("Line 4"); System.out.println("Bob says hi."); } } 

对于完整的控制台function,您可以覆盖JTextAreas文本处理方法,并在选择开始位于JTextArea中最后一行之前或之后将键/鼠标侦听器添加到setEnabled(boolean),并在输入键为时执行命令按下。

希望现在有所帮助。 (我可能会稍后再回来编辑,不要太难看,等等)