2014-02-17 66 views
0

我在JTextArea中設置文本時遇到問題,我嘗試了setText(我更喜歡)並追加。我不知道問題出在哪裏,我得到了客戶端 - 服務器應用程序。我希望把他們的服務器中的JTextField發送消息,但是我無法在這裏是我的代碼:JTextArea setText無法正常工作

客戶端代碼是否正確reciving消息:

try 
    { 


     Socket socket = new Socket("localhost", PORT); 
     BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); 
     DataOutputStream output = new DataOutputStream(socket.getOutputStream()); 
     BufferedReader serverInput = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

     output.writeBytes(outputString + "\n"); 
     inputString = serverInput.readLine(); // private String inputString 
     mymodel.setTextArea(inputString); // this is not working 
     System.out.println(inputString); // this is working 
     socket.close(); 

    } 
    catch... 

setTextArea方法:

public void setTextArea(String string) 
{ 
    MyPanel mypanel = new MyPanel(); 
    mypanel.textArea.setText(string); // debugger shows that the string contains message from server 
} 

由於setter方法不工作,我已經設置textarea爲public,實際上這個也不工作。我不知道問題出在哪裏,調試器也不幫助我。

尋找你的答案

編輯:

JTextTable代碼:

textArea = new JTextArea(1, 30); 
textArea.setEditable(false); 
panel.add(textArea, c); 

回答

0

嘗試獲得通過的getter訪問。 像

public JTextArea getTextArea() 
{ 
    return jTextAreaField; 
} 

然後

getTextArea().append("ur text"); 
1

你創建的每一次setTextArea方法被調用MyPanel一個新的實例,這意味着什麼都屏幕上沒有被用來應用你發送的文本。

相反,你應該使用創建顯示在屏幕上的MyPanel原始實例...

它也不可能確定如果要調用從事件調度的內容阻塞I/O線程或從不同線程與UI進行交互。在這兩種情況下,這是極不推薦的

看看Concurrency in Swing更多細節

1

主要有兩個問題:

  1. 你同一個線程的IO,上執行UI修改其你永遠不應該這樣做。考慮使用SwingWorker進行I/O操作。

  2. setTextArea你沒有訪問你已有的MyPanel實例,但創建一個新實例。因此,改變也不會在你已經有MyPanel實例來完成...

+0

我怎麼能訪問其他類的現有MyPanel的實例呢? – bbZ

+0

如果你按照我的第一點來看教程,它會比黑客更容易(儘管絕對有可能) – MByD

1
JTextArea t=new JTextArea(); 
    t.append("Text"); 
    no Method in java to set Text for JTextArea. 
    the append method to add text in JTextArea