Reputation: 2055
I know how to create one button and an Action Listener for it. But I want to have several buttons and actionListeners for them doing separate actions unrelated to each other.
Example:
protected JButton x;
x = new JButton("add");
x.addActionListener(this);
public void actionPerformed(ActionEvent evt) { //code.....}
Now I want to have other buttons which may hav different functions like subtract, multiply etc. please suggest. thanks
Upvotes: 10
Views: 93330
Reputation: 61
how about...
protected JButton x, z, a, b,c;
x = new JButton("add x");
z = new JButton("add z");
a = new JButton("add a");
b = new JButton("add b");
c = new JButton("add c");
x.addActionListener(this);
z.addActionListener(this);
a.addActionListener(this);
b.addActionListener(this);
c.addActionListener(this);
then
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource()==x)
{
//do something
}
else if (evt.getSource()==z)
{
//do something
}
else if (evt.getSource()==a)
{
//do something
}
else if (evt.getSource()==b)
{
//do something
}
else if (evt.getSource()==c)
{
//do something
}
}
this is always works for me, but honestly I'm not sure if it's not bad practice
Upvotes: 6
Reputation: 137432
You can create different action listener instances, not using your class:
x.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e)
{ ... }
});
There are several other methods to create action listener, just like any class, but for short actions this (anonymous class) is a convenient way.
Upvotes: 1
Reputation: 7943
You just need to create new instance of the ActionListener
each time.
BTW for lots of reasons it is recommended to use Action
's instead.
Here is nice resource which also explains why you should go with using Actions over ActionListeners, a Java tutorial titled How to Use Actions
EDIT: @fmucar is right you can do it all in a single ActionListener. Though having separate functional Actions allows you to reuse them independently.
Upvotes: 1
Reputation: 7507
What about:
JButton addButton = new JButton( new AbstractAction("add") {
@Override
public void actionPerformed( ActionEvent e ) {
// add Action
}
});
JButton substractButton = new JButton( new AbstractAction("substract") {
@Override
public void actionPerformed( ActionEvent e ) {
// substract Action
}
});
Upvotes: 20
Reputation: 6124
Use inner classes:
x = new JButton("add");
x.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
//your code here
}
}
);
Upvotes: 12
Reputation: 14558
You can either use ActionEvent.getSource()
to decide the source and act accordingly or you can define different ActionListeners
for each of them.
Upvotes: 5