所以我有一個MainWindow.java
,它創建了包含所有控件和事物的窗口。我在窗口上放置了菜單欄對象,菜單欄中的其中一個選項是使程序成爲服務器。因此,這裏的主窗口如下所示:使用MainWindow函數的Java
public class MainWindow extends javax.swing.JFrame {
//all code including menubar click action handler
//Server.start()
}
當您單擊該選項,將進入Server.java
類,並啓動服務器。下面是類的骨架:
public class Server {
public static void start(String port) {
try {
startServer(Integer.parseInt(port));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void startServer(int PORT) throws Exception {
...
}
private static class ClientListenThread extends Thread {
public ClientListenThread(Socket socket, int ClientNumber){
...
}
public void run() {
...
}
}
private static class ServerSendThread extends Thread {
public ServerSendThread(Socket socket) {
...
}
public void run() {
...
}
}
}
現在的問題是,一旦它得到了Server
類裏面,它監聽連接,並連接正常,但我不能回去MainWindow
類。它保持在Server
課程中。我不能,因爲它說
Cannot make a static reference to the non-static method function() from the type MainWindow
我甚至試圖把所有的Server
類代碼到MainWindow類或它上面,但Java的不喜歡,並表示這樣做MainWindow.function()
即使調用MainWindow
功能希望它在一個單獨的文件。
我到底該如何在Server類中引用MainWindow
函數?還是有更好的方法來解決這個問題?
我還有1個問題。因此,當您從菜單欄中選擇服務器選項時,「MainWindow」類具有菜單欄 - 出現一個彈出窗口。該彈出窗口由另一個名爲「ServerWindow」的類處理。它有一些字段,您可以在類似的端口號中輸入內容,然後單擊確定。一旦你點擊確定,'ServerWindow'將所有類型的信息發送到'Server'類。有一個名爲'draw()'的'MainWindow'函數,它有如下形式:'Graphics g = this.getGraphics();'。 – Richard
當我從'ServerWindow'調用'draw()'時,'this.getGraphics()'引用服務器的窗口,而不是菜單欄的原始窗口。我如何解決這個問題? – Richard
您可以在ServerWindow類的構造函數中傳入對MainWindow對象的引用。然後在你傳入的MainWindow對象上調用draw()函數。 –