Java - Scanner和JTextFields的问题

时间:2015-04-07 10:36:55

标签: java swing java.util.scanner jtextfield

这是我第一次在Scanner中使用JFrame时使用JTextFields和1 JTextArea,我遇到了问题。当我在文本字段中输入字符串时,扫描仪能够毫无问题地拾取它,我也可以将其打印出来。

但是当我尝试在textarea中输入一个字符串时,扫描仪不会拾取它。我已尝试在文本字段中将focusable设置为false,但扫描程序仍然没有拾取在textarea中输入的字符串。

知道为什么会这样吗?

修改 我的错。它是1 JTextField和1 JTextArea

这是我的客户端类:

public class Client implements Runnable{

    //Globals
    Socket sock;
    Scanner input;
    Scanner send = new Scanner(System.in);
    PrintWriter output;

    public Client (Socket X) {
        this.sock = X;
    }

    //@Override
    public void run() {
        try {
            try {
                input = new Scanner(sock.getInputStream());
                output = new PrintWriter(sock.getOutputStream());
                output.flush();
                CheckStream();
            }
            finally {
                sock.close();
            }
        }
        catch (Exception E) {
            System.out.print(E);
        }
    }

    public void Disconnect() throws IOException{
        output.println(ChatRoom.Username + " has disconnected!");
        output.flush();
        sock.close();
        JOptionPane.showMessageDialog(null, "You disconnected!");
        System.exit(0);
    }

    public void CheckStream() {
        while (true) {
            Receive();
        }
    }

    public void Receive() {
        if (input.hasNext()) {
            String message = input.nextLine();
            //the problem is with "message"
            //it can read the first textfield but not the second
            System.out.println(message);

            if (message.contains("#?!")) {
                String tempCurrUsers = message.substring(3);
                tempCurrUsers = tempCurrUsers.replace("[", "");
                tempCurrUsers = tempCurrUsers.replace("]", "");

                String[] CurrentUsers = tempCurrUsers.split(", ");

                ChatRoom.JL_CurrentUsersDisplay.setListData(CurrentUsers);
            }
            else {
                System.out.println(message);
                ChatRoom.TA_ChatDisplay.append(message + "\n");
            }
        }
    }

    public void Send(String X) {
        output.println(ChatRoom.Username + ": " + X);
        output.flush();
        ChatRoom.TF_MessageBox.setText("");
        //ChatRoom.TA_ChatDisplay.append(ChatRoom.Username+": " + X + "\n");

    }
}

1 个答案:

答案 0 :(得分:3)

我不认为在Swing中使用Scanner(除非你在谈论条形码扫描器)。我相信你想要使用像

这样的东西
String someText = textField1.getText();

查看How to Use Text Fields