Search code examples
javauser-interfaceconstructorjbuttongetter-setter

Using JButton ActionListener to run different class in same package


I'm having an issue as I'm relatively new to GUI.

Basically to put everyone in the picture, I have a package which consists of:

  • my MainClass (Includes the GUI)
  • A seperate Class (Don't want it to run unless button is clicked)
  • Another seperate class which I don't want to run unless it's specific button is clicked.

So my MainClass GUI is basically the controller.

However, I honestly have no clue how to go about it. Was told to have to create a constructor and use getters/setters? However I still don't understand how to call that specific class whilst leaving the other off "Turned off".

Thanks.


Solution

  • Well, there are quite a few ways to do this... Either you create anonymous listeners for each button, and then, depending on what you want to do, trigger methods in other classes or the like;

    JButton b1 = new JButton();
    b1.addActionListener(new ActionListener(){
    
        public void actionPerformed(ActionEvent e)
        {
            //Do something!
            OtherClass other = new OtherClass();
            other.myMethod();
        }
    });
    
    JButton b2 = new JButton();
    b2.addActionListener(new ActionListener(){
    
        public void actionPerformed(ActionEvent e)
        {
            //Do something else!
            ...
        }
    });
    

    Alternatively, you use the command string and associate a unique command (made final, preferably) which you compare with when receiving a actionPerformed in a common listener implementation;

    //In your class, somewhere...
    public final static String CMD_PRESSED_B1 = "CMD_PRESSED_B1";
    public final static String CMD_PRESSED_B2 = "CMD_PRESSED_B2";
    
    //Create buttons
    JButton b1 = new JButton();
    JButton b2 = new JButton();
    
    //Assign listeners, in this case "this", but it could be any instance implementing ActionListener, since the CMDs above are declared public static
    b1.addActionListener(this);
    b2.addActionListener(this);
    
    //Assign the unique commands...
    b1.setActionCommand(CMD_PRESSED_B1);
    b2.setActionCommand(CMD_PRESSED_B2);
    

    And then, in your listener implementation;

    public void actionPerformed(ActionEvent e)
    {
        if (e.getActionCommand().equals(CMD_PRESSED_B1)
        {
            //Do something!
            OtherClass other = new OtherClass();
            other.myMethod();
        }
    
        else if (e.getActionCommand().equals(CMD_PRESSED_B2)
        {
            //Do something else!
            ...
        }
    }