Java using MainWindow functions

2019-09-09 09:19发布

问题:

So I have a MainWindow.java that creates the window with all the controls and things. I put a menubar object on the window, one of the options in the menubar is make the program a server. So here's the main window looks like this:

public class MainWindow extends javax.swing.JFrame {
     //all code including menubar click action handler
     //Server.start()
}

When you click the option, it goes into the Server.java class and starts the server. Here's the skeleton of that class:

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() {
            ...
        }
    }
}

The problem now is that once it gets inside the Server class, it listens for connections and connects fine but I just can't go back to the MainWindow class. It stays within the Server class. I can't even call the MainWindow functions by doing MainWindow.function() because it says

Cannot make a static reference to the non-static method function() from the type MainWindow

I even tried putting all of the Server class code into the MainWindow class or just above it but Java didn't like that and said it wanted it in a separate file.

How exactly do I reference MainWindow functions from within the Server class? Or is there a better way of going about this?

回答1:

You need to either create an instance of the MainWindow class using for instance MainWindow m = new MainWindow() and then calling the function as m.function(), or declare your function as static.

Static means that you can call a function without creating an instance of the object. This is why you get the error, since your function is not static, so it requires an instance of the object to be called.

You'll also want to make sure that the MainWindow class is imported into the Server class.