【问题标题】:How to listen to JTextArea如何收听 JTextArea
【发布时间】:2012-03-03 10:06:10
【问题描述】:

我正在创建一个个人 Java 终端,我需要它来做一些我现在不太了解的事情。我需要程序监听输入到 JTextArea 的内容,同时还知道程序将始终显示

[USERNAME]@[OPERATING SYSTEM]:~$

当“Enter”被按下时。而且我还需要程序将上述部分设置为不可编辑,并允许在永久声明后设置字符输入。 如果有人能帮我解决这个问题,我的程序如下,然后是监听器的代码,很可能需要大量编辑。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import java.io.*;

public class testGUI extends JFrame {
      boolean _active = true;
     String _username = System.getProperty("user.name").toLowerCase();
     String _os = System.getProperty("os.name").trim().toLowerCase();
     JTextArea _commandLine = new JTextArea(_username + "@" + _os + ":~$ ");

    public testGUI() {
        super("Java Terminal");

        setSize(800,600);
        setLocation(100,100);

        setDefaultCloseOperation(EXIT_ON_CLOSE);

        GUISetup();

        setVisible(true);
    }

    public void GUISetup() {
        add(_commandLine);
        _commandLine.addActionListener(new CommandLineListener());
    }


        public static void main(String[] args) {
        new testGUI();
    }
}   

监听器代码如下。

        try {
        while(_active) {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.print(_username + "@" + _os + ":~$ ");
            String command = br.readLine();
                if(command.equals("cf")) {
                    new commandCreateFile();
                } else if(command.equals("cof")) {
                    new commandCompile();
                } else if(command.equals("help")) {
                    System.out.println("Commands");
                    System.out.println(" cf              - Creates .java files, does not compile.");
                    System.out.println(" ccf             - Creates .java files, compiles on creation.");
                    System.out.println(" help            - Shows help documentation.");
                } else if(command.equals("exit")) {
                    System.out.print("Are you sure you want to exit? (Y/N) ");
                    String exit = br.readLine();
                    if(exit.equalsIgnoreCase("y")) {
                    System.exit(0);
                    }
                } else if(command.isEmpty()) {
                    // do nothing.
                } else {
                    System.out.println("\"" + command + "\" does not exist. Please review the \"help\" menu");
                }
        }
    } catch(Exception ex) {
        System.out.println("There was a problem: " + ex);
    }

【问题讨论】:

    标签: java swing user-interface listener jtextarea


    【解决方案1】:

    使用附加到JTextArea's DocumentDocumentListener 和附加到DocumentDocumentFilter 来检查允许进行哪个编辑。

    【讨论】:

    • 这个我不明白,通过使用JTextArea的文档,我需要附加一个适当的文档吗?
    猜你喜欢
    • 1970-01-01
    • 2014-05-22
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 2017-04-06
    • 2014-05-18
    • 1970-01-01
    相关资源
    最近更新 更多