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

时间:2014-02-05 11:50:03

标签: java swing console jtextarea

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

或者,更具体地说,如何在我的FTP程序中添加一个JTextArea作为控制台,并添加像C:\ tmp \ -list这样的命令,前面添加了不可编辑的文本?

2 个答案:

答案 0 :(得分:2)

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

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

来自JavaDoc:

  

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

请注意您必须自己添加换行符,例如

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

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


如果您想拥有一个真正的自制控制台,请查看LanternaJLine

答案 1 :(得分:0)

这是一个非常不完整的答案,但它是一个开始。此代码适用于扩展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.");
    }
}

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

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