How to use methods from two classes in eachother in Java?

java

Solution

Some class must be building both of these objects--the GUI and the server--and it should make each aware of the other. For example, say the main class is `ServerApplication`. I'll use standard Java convention of starting class names with an uppercase letter for clarity.

class ServerApplication {
    Server server;
    ServerFrame gui;

    public static void main(String []) {
        server = new Server(...);
        gui = new ServerFrame(server);
        server.setGui(gui);
    }
}

Each class should store the reference to the other as well.

class Server {
    ServerFrame gui;

    public void setGui(ServerFrame gui) {
        this.gui = gui;
    }

    ...
}

class ServerFrame extends JFrame {
    Server server;

    public ServerFrame(Server server) {
        this.server = server;
    }

    ...
}

Problem

I've been looking around and I only found one answer which wasn't clear enough, to me at least. I am building a very basic chat application with a GUI and I have separated the GUI from the connection stuff. Now I need to call one method from GUI in server class and vice versa. But I don't quite understand how to do it (even with "this"). Here's what a part of code looks like (this is a class named server_frame): ``` textField.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { srv.sendData(arg0.getActionCommand()); } catch (Exception e) { e.printStackTrace(); } textField.setText(""); } } ); ``` This is a code from server_frame, srv is an object from the other class (server) which contains sendData method, and I probably didn't define it correctly so hopefully someone could make a definition of it. On the other side class server from which object srv was made contains method using JTextArea displayArea from server_frame in this code: ``` private void displayMessage(final String message){ sf = new server_frame(); SwingUtilities.invokeLater(new Runnable(){ public void run(){ sf.displayArea.append(message); } } ); } ``` Yet again sf is an object made of server_frame and yet again probably missdefined :) Hopefully that was clear enough, sadly I tried the searching but it just didn't give me the results I was looking for, if you need any more info I will gladly add it! Thanks for reading, Mr.P. P.S. Please don't mind if I made terminology mishaps, I am still quite new to java and open to any corrections!

Original source