jibbajava
jibbajava

Reputation: 17

Multiple buttons and multiple listeners doing various operations Java Swing

How can I have multiple buttons and multiple listeners doing various operations in java swing. Here is an example of what I have, I can redirect to the AddStudent class but the button to redirect to the AddAdult class wont redirect to the AddAdult class.

private class ButtonHandler implements ActionListener {
  // handle button event
  public void actionPerformed( ActionEvent Student ) {
    if ( Student.getSource() == button1 ){
      try {
        AddStudent newmember = new AddStudent();
        newmember.setVisible( true );
      } catch ( Exception e1 ) {
        e1.printStackTrace();
      }
  }
}


public void actionPerformed( ActionEvent Adult ) {
  if ( Adult.getSource() == button2 ){
    try {
      AddAdult newmember = new AddAdult();
      newmember.setVisible( true );
    } catch ( Exception e1 ) {
      e1.printStackTrace();
    }
  }
}

Thanks for any help in advance.

Upvotes: 0

Views: 10281

Answers (3)

mKorbel
mKorbel

Reputation: 109813

you have three another ways

1) use Swing Action

       myPanel.add(new JButton(new AbstractAction("some narrative") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                //some stuff
            }
        }));

2) use inner ActionListener

code

myButton.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent ae) {
        //some stuff
    }
});

3) use EventHandler

Upvotes: 1

paulhudson
paulhudson

Reputation: 268

If you want to have multiple handlers, you can define multiple classes each implementing ActionListener interface with appropriate logic implemented and attach it to appropriate buttons. If you want to use single handler for all buttons, you can use getActionCommand() (more clear than using getSource()) method of ActionEvent to check for the button text and implement your handling logic accordingly using if else.

Upvotes: 1

Robin
Robin

Reputation: 36601

You can attach an ActionListener to each JButton, as explained in the Swing tutorial for buttons

So you will end up with something like

JButton firstButton = ...;
firstButton.addActionListener( myFirstButtonActionListener );

JButton secondButton = ...;
secondButton.addActionListener( mySecondActionListener );

//add them to a UI
contentPane.add( firstButton );
contentPane.add( secondButton );

For more specific questions about your program and your button you will need to provide us with more code then is currently available in your question (in other words, post an SSCCE)

Upvotes: 4

Related Questions