How do you add an ActionListener onto a JButton in Java

197,716

Solution 1

Two ways:

1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.

2. Use anonymous inner classes:

jBtnSelection.addActionListener(new ActionListener() { 
  public void actionPerformed(ActionEvent e) { 
    selectionButtonPressed();
  } 
} );

Later, you'll have to define selectionButtonPressed(). This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.

2, Updated. Since Java 8 introduced lambda expressions, you can say essentially the same thing as #2 but use fewer characters:

jBtnSelection.addActionListener(e -> selectionButtonPressed());

In this case, e is the ActionEvent. This works because the ActionListener interface has only one method, actionPerformed(ActionEvent e).

The second method also allows you to call the selectionButtonPressed method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).

Solution 2

Your best bet is to review the Java Swing tutorials, specifically the tutorial on Buttons.

The short code snippet is:

jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );

Solution 3

I don't know if this works but I made the variable names

public abstract class beep implements ActionListener {
    public static void main(String[] args) {
        JFrame f = new JFrame("beeper");
        JButton button = new JButton("Beep me");
        f.setVisible(true);
        f.setSize(300, 200);
        f.add(button);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Insert code here
            }
        });
    }
}
Share:
197,716
user3703701
Author by

user3703701

Updated on November 18, 2021

Comments

  • user3703701
    user3703701 over 2 years
    private JButton jBtnDrawCircle = new JButton("Circle");
    private JButton jBtnDrawSquare = new JButton("Square");
    private JButton jBtnDrawTriangle = new JButton("Triangle");
    private JButton jBtnSelection = new JButton("Selection");
    

    How do I add action listeners to these buttons, so that from a main method I can call actionperformed on them, so when they are clicked I can call them in my program?

  • David Koelle
    David Koelle over 13 years
    @Sara - Glad that helped! If you can think of any further clarifications, I'll be happy to add them to this answer.
  • Marko Kitonjics
    Marko Kitonjics over 8 years
    When someone asks: How can a component handle its own events? is the answer to that question to use anonymous inner classes like you here showed?
  • David Koelle
    David Koelle over 8 years
    Not necessarily. You could have a custom component (e.g., something that extends JComponent) and also implements ActionListener, MouseListener, etc.
  • DoesData
    DoesData over 6 years
    Don't you have to add @Override for actionPerformed?
  • David Koelle
    David Koelle over 6 years
    You don't have to, but it's a good practice to do that. Using Override is a good practice because it helps you recognize when you think you've implemented a method from the super class or interface, but really you've given your function an incorrect method signature. But using Override is not required when writing a Java program.
  • john ktejik
    john ktejik almost 6 years
    Java 9 is forcing me to use @override, or declare it as a lambda function\
  • RW77
    RW77 almost 3 years
    @DavidKoelle - So, what are the disadvantages of using multiple if(ev.getSource()) statements all in one actionPerformed() method? Will it slow down your program a lot? Or is it for readability? Thanks.
  • David Koelle
    David Koelle almost 3 years
    Readability, extensibility, and maintenance. Imagine you're going to remove an existing button - now you have to remember to remove code from multiple places. Or if you're going to add a new button, you're adding functionality to multiple places. Also, you're having to do a lot of, "If it's this source, do this; if it's that source, do that" and that's not very object-oriented. The object should know how to do its thing without other code being involved.