38
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?

montrealist
  • 5,593
  • 12
  • 46
  • 68
user37037
  • 381
  • 1
  • 3
  • 3

3 Answers3

68

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()).

David Koelle
  • 20,726
  • 23
  • 93
  • 130
  • @Sara - Glad that helped! If you can think of any further clarifications, I'll be happy to add them to this answer. – David Koelle Jan 04 '11 at 04:41
  • 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? – Marko Kitonjics Feb 24 '16 at 10:13
  • Not necessarily. You could have a custom component (e.g., something that extends JComponent) and also implements ActionListener, MouseListener, etc. – David Koelle Feb 24 '16 at 14:18
  • Don't you have to add @Override for actionPerformed? – DoesData Nov 03 '17 at 13:47
  • 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. – David Koelle Nov 03 '17 at 21:19
  • Java 9 is forcing me to use @override, or declare it as a lambda function\ – john k Jul 09 '18 at 04:22
  • 1
    @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. – RW77 Jul 29 '21 at 23:06
  • 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. – David Koelle Jul 30 '21 at 01:30
8

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*/ );
Alex B
  • 24,678
  • 14
  • 64
  • 87
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
            }
        });
    }
}
User123
  • 476
  • 7
  • 22