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

I look around and I found only one answer that was not clear enough, at least for me.

I am creating a very basic GUI chat application and I have separated the GUI from the connection materials. Now I need to call one method from the GUI in the server class and vice versa. But I do not quite understand how to do this (even with "this"). This is what the piece of code looks like (this is a class called 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 the code from server_frame, srv is an object from another class (server) that contains the sendData method, and I probably did not define it correctly, so hopefully someone can make its definition.

On the other hand, the class server from which the srv object was created contains a method that uses 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); } } ); } 

And again, sf is an object created from server_frame, and, again, possibly missed :)

I hope this was clear enough, unfortunately, I tried the search, but it just did not give me the results that I was looking for, if you need more information, I will be happy to add it!

Thank you for reading,

Mr.P.

PS Please do not mind if I made failures in the terminology, I am still new to java and open to any corrections!

+4
source share
2 answers

Some class should build both of these objects - a graphical interface and a server - and it should inform each of them. For example, suppose the main class is ServerApplication . For clarity, I use the standard Java convention for starting capitalized class names.

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

Each class must store a link to another.

 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; } ... } 
+3
source

I think you can look for the syntax of ClassName.this.methodName. this in these action initiators refers to the anonymous class that you created. If you used the syntax above, you are referring to a class containing an anonymous class.

Or, if you are looking for a private field in a class, you should do ClassName.this.privateField

0
source

All Articles