JTextField如何在文本中阅读

时间:2015-12-12 23:50:13

标签: java

在我的GUI.java类中,我有以下功能:

public void setChat(String text)
{
   chat.append(text);
}

public void getInput(String text)
{
   String read = input.getText();
}

我正在尝试使用我的getInput()方法来设置我将用于其余代码的用户名,但我似乎无法从Client.java中的TextField中正确读取它。我在获取原版时遇到了很多麻烦:

String username = gui.getInput();

(这当然也没有用)。有人可以帮我读一下TextField条目并将其分配给我的用户名String吗?

import java.io.*;
import java.net.*;

public class Client
{      
   public static void main(String [] args) throws IOException
   {
   GUI gui = new GUI();
   javax.swing.SwingUtilities.invokeLater(new Runnable()
   {
     public void run()
     {
        //GUI gui = new GUI();
     }
  }); 

  String username = "";      
  gui.setChat("  Enter the username you would like to use for the duration of the chat session.\n");
  if (username == "")
  {
     System.out.println("Press Any Key To Continue...");
     new java.util.Scanner(System.in).nextLine();
     gui.getInput(username);
     gui.setChat("  Your username is now: " + username + ".\n");
  }
 }
}

编辑1

GUI.java类:

String getInput(String text)
{
   return input.getText();
}

Client.java类:

  String username;
  gui.setChat("  Enter the username you would like to use for the duration of the chat session.\n");
  username = gui.getInput();

  System.out.println("Press Any Key To Continue...");
  new java.util.Scanner(System.in).nextLine();
  gui.setChat("  Your username is now: " + username + ".\n");

错误:

Client.java:19: error: method getInput in class GUI cannot be applied to given types;
  username = gui.getInput();
                ^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 error

1 个答案:

答案 0 :(得分:0)

public void getInput(){
    return input.getText();
}

然后在主

username = "" + gui.getInput();