[英]Java Swing Jbutton accessing a pressed button from another class?
[英]Accessing a Java Swing GUI from another class
我有三個類 - 類1,它創建類2(GUI),2類的一個實例,它實現它試圖更新GUI GUI和類3。
在第1類中,我像這樣創建GUI:
s = new ServerSocket(6067);
//while(true){
Socket ClientSocket = s.accept(); // Accept connections
// Create instance of the GUI (class 2) on a new thread
work w = cpd.new work();
Thread t = new Thread(w);
t.start();
// Create instance of class 3 that uses the GUI on a new thread
Charger cpt = new ChargingPoint(ClientSocket, w.gui);
cpt.start();
//}
class work implements Runnable{
GUI gui;
public void run(){
try{
gui = new GUI();
gui.setVisible(true);
}
catch(Exception e){}
}
}
在第2類中,我實現了GUI,並具有一些允許對其進行更新的方法,例如:
public void updateConsole(String text){
Console.append(text + "\n");
}
在第3類中,我嘗試使用如下所示的這些方法,但是當到達這樣的語句時,代碼將卡住:
gui.updateConsole("Data: " + data);
在我將GUI類(第2類)作為主要類之前,這對我已經起作用了。 我將此實例傳遞給所有其他類,他們可以使用它來更新GUI,而不會出現任何問題。 但是,這次我要從另一個類(類1)創建GUI,並且此方法不再起作用,並且我正在努力找出原因。
任何建議將不勝感激。
我將嘗試為您提供工具進行調試。
嘗試使用eclipse或類似的調試器。 http://www.vogella.com/articles/EclipseDebugging/article.html
首先檢查class2實際上是否在回調gui類的正確實例。
使用調試器,您可以找到一個“對象ID”。 這將告訴您對象在內存中的唯一ID。 通常是內存指針。 檢查ChargingPoint中的ID是否與Work類中創建的ID相匹配。 在錯誤的類上運行方法是回調最常見的錯誤。
然后繼續在gui.updateConsole中放置一個斷點,並進入代碼。
這應該可以迅速揭示問題。
問候
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.