I know how to create one button and an Action Listener for it. But I want to h开发者_运维知识库ave 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
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
}
});
Use inner classes:
x = new JButton("add");
x.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
//your code here
}
}
);
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
You can either use ActionEvent.getSource()
to decide the source and act accordingly or you can define different ActionListeners
for each of them.
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.
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.
精彩评论