We help IT Professionals succeed at work.

Where to put the JFrame actionlisteners when programming client-server with sockets.

Woestijnvis
Woestijnvis asked
on
I am programming a client server program over sockets.
I have a main class where I Open a JFrame class and inside the JFrame I have another class with a panel. This panel has 2 buttons. When I click this buttons I need to send a command to the server.
As my Buttons are in the panel class, my actionlisteners for this buttons are too. My socket is initiated in the main class and is in a while(true) loop.
How can I get to the socket from my actionlisteners, as my socket instance is unknown in Jpanel class. How can I fix this? I can't pass my socket object to the frame, I tried and that doesnt work.
Comment
Watch Question

Mick BarryJava Developer
Top Expert 2010

Commented:
either pass a reference to your main class so the listener can call it from there

or add a method to the class that contains the class to add the listener

public void addActionListener(ActionListener l) {
   button.addActionListener(l);
}

you can then call that from your main class to add a listtener which owuld have access to socket
Java Developer
Top Expert 2010
Commented:
i'd use the latter

class A {
   B b;
   Socket socket s;

   public void createGui() {
      b = new B();
      ...
      b.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent event) {
             // button pressed
         }
     });
   
}

class B {
   Jbutton button


   public void addActionListener(ActionListener l) {
      button.addActionListener(l);
   }
}

Author

Commented:
Genius,
I understand your solution, but my button is in a panel, my panel is in a frame and my frame is being called by a main class. My socket is in the main class. The easiest step would be to bring my socket in the frame class. But thats not good programming because I want MVC.

How can I get the actionListener of the button up to the main class?

Eli
Commented:
Action listener inside Main

public static void main(String args[]){
JButton yourButton = new JButton();
.....
yourButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent event) {
             // button pressed
         }
     });


}



================================================================


import java.awt.*;
import java.awt.event.*;

public class YourCLass implements ActionListener {
      public static void main(String[] args) {

            YourButton.addActionListener(this);
      }

      }

      public void actionPerformed(ActionEvent e) {
           Your Action Listner events
      }


}



Is this what do you mean ?
Kevin CrossChief Technology Officer
Most Valuable Expert 2011

Commented:
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.