Reputation: 33
Here is my ButtonListener class in my GUI. I have several buttons within it, that when clicked, I want to call a certain method for each one, for instance:
public class ButtonListener implements ActionListener{
public void actionPerformed( ActionEvent event ){
if (event.getSource( ) == buttonA)
If button A is selected, I want to call a method and have its return statement displayed.
Upvotes: 0
Views: 383
Reputation: 3762
If I understand it, you should do the following (just an example):
class X{
JButton firstButton;
JButton secondButton;
public X(){
firstButton=new JButton("first");firstButton.setActionCommand("FB");
secondButton=new JButton("second");secondButton.setActionCommand("SB");
}//constructor closing
public void method1(){}
public void method2(){}
class EventHandler extends ActionListener{
public void ActionPerformed(ActionEvent e){
String action=e.getActionCommand();
if(action.equals("FB"))method1();
else if(action.equals("SB"))method2();
}//
}//inner-class closing
}//calss closing
Upvotes: 0
Reputation: 180
I think it's good practise to use a switch in this case because you've said you have several buttons.
public void actionPerformed(ActionEvent e) {
switch (e.getSource())
case buttonA:
buttonACode();
break;
case buttonB:
buttonBCode();
break;
default:
someDefaultAction();
break;
}
If you would like to display the returned result you can replace buttonACode();
with System.out.println(buttonACode());
Upvotes: 0
Reputation: 1774
(If I understand you correctly)
You could have
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonA)
{
ButtonAImpl x = new ButtonAImpl();
x.myMethod();
}
if (e.getSource() == buttonB)
{
ButtonBImpl y = new ButtonBImpl();
y.myMethod();
}
}
You may want to look at some design patterns to help in this scenaro...
MVC - http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
MVP - http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter
Upvotes: 1