2015-12-12 34 views
0

看在我的GUI.java類,我有以下功能:JTextField中如何在文本

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

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

我想用我的getInput()方法來設置我將使用剩下的用戶名我的代碼,但我似乎無法正確從我的Client.java中的TextField中讀取它。我在獲取原件時遇到了很多問題:

字符串username = gui.getInput();

(這當然也沒有工作)。有人可以幫我閱讀一個TextField條目並將其分配給我的用戶名字符串?

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"); 
    } 
} 
} 

EDIT 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 
+0

getInput()應返回字符串而不是具有String參數。然後你可以使用username = gui.getInput()。 – WillShackleford

+0

每當我嘗試返回時,它會給我錯誤。 –

+0

列出您的問題中的錯誤。 – WillShackleford

回答

0

嘗試

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

然後在主

username = "" + gui.getInput(); 
+1

請在答案中加入一些解釋。這將有助於OP和其他訪問者。 – Jayan

+0

不好。 「GUI.java:95:錯誤:不兼容的類型:意外返回值」。 –

+0

它應該是public String getInput()不是public void getInput(),也不需要添加「」+,因爲它已經是一個字符串了。 – WillShackleford