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
The getSource method is used in the actionPerformed method to determine which button was clicked. For more information, see Event Handling.
An action event occurs, whenever an action is performed by the user. Examples: When the user clicks a button, chooses a menu item, presses Enter in a text field. The result is that an actionPerformed message is sent to all action listeners that are registered on the relevant component.
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
}
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With