Reputation: 4432
I always make an event listener for buttons and such like this:
class MyClass implements extends JPanel implements ActionListener{
JButton btn1, btn2, btn3;
public Myclass(){
....
btn1 = new JButton("button 1");
btn1.addActionListener(this);
....
}
public void actionPerformed(ActionEvent e) {
Object action = e.getSource();
if(action = btn1){
functionForBTN1();
}
else if(action = btn2){
functionForBTN2();
}
else if(action = btn3){
functionForBTN3();
}
}
public void functionForBTN1(){...}
public void functionForBTN2(){...}
public void functionForBTN3(){...}
}
Is it possible to direct the event directly to a method instead of the actionPerformed()
method? something like (pseudo-code):
class MyClass implements extends JPanel implements ActionListener{
JButton btn1, btn2, btn3;
public Myclass(){
....
btn1 = new JButton("button 1");
btn1.addActionListener(this.functionForBTN1());
....
}
public void functionForBTN1(){...}
public void functionForBTN2(){...}
public void functionForBTN3(){...}
}
Upvotes: 1
Views: 79
Reputation: 16067
As Maroun Maroun said an anonymous class is a good idea. With java-8 you could also use a lamdba which makes the code slightly nicer;
btn1.addActionListener(event -> functionForBTN1());
Upvotes: 1
Reputation: 1832
If you're using Java 8, you can accomplish this using a lambda expression.
btn1.addActionListener(e -> this.functionForBTN1());
Prior to Java 8, you could create an anonymous ActionListener to acomplish the same task.
btn1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
this.functionForBTN1();
}
});
Upvotes: 3
Reputation: 96018
You can use anonymous classes:
btn1.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent e) {
// ....
}
});
However, if you want to add it like you did in your second snippet, you can do something like:
final ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
if (e.getSource() == btn1) {
//...
} else if (e.getSource() == btn2) {
//...
}
}
};
And then:
btn1.addActionListener(listener);
btn2.addActionListener(listener);
I personally prefer anonymous classes as long as they're readable and not too long.
Upvotes: 1