How does Java know when a JButton has been pressed?

0
2
Asked By VelvetMango42 On

I'm learning Java Swing and trying to understand how event handling works. In this code, the frame implements ActionListener and registers itself with button.addActionListener(this). When the button is clicked, actionPerformed(ActionEvent e) runs, and the code checks whether e.getSource() == button before printing a message.

How does the ActionEvent know that the action was a button press, and how does Java know which method to call? Is the button keeping track of its listeners somehow? I'm also confused about anonymous classes—are they creating an unnamed class instance, or something like a special superclass instance?

3 Answers

Answered By CopperLark19 On

A JButton maintains a collection of ActionListener objects. Calling addActionListener(this) adds the current MyFrame instance to that collection. When the button is activated, it creates an ActionEvent and invokes actionPerformed on each registered listener, passing the event as the argument. In effect, one object is simply calling a method on another; this is commonly associated with the observer pattern.

MistyOrbit6 -

The operating system reports input events, such as mouse clicks, to the GUI toolkit. Swing turns the relevant input into a button action and dispatches it to the listeners registered with that button.

Answered By AmberCedar31 On

The Java and JavaScript event systems are different, so JavaScript experience may not map directly here. Also, an anonymous class is an unnamed class declared and instantiated at the same time. For example, you could pass new ActionListener() { ... } directly to addActionListener instead of making MyFrame implement ActionListener. It is not a superclass instance; it is an instance of a compiler-generated unnamed class that implements the interface.

Answered By QuietPine7 On

There’s no magic involved. JButton detects the user interaction and creates an ActionEvent describing it. Because you registered this object with button.addActionListener(this), the button calls that object’s actionPerformed method when the action occurs. The event’s source is the button that generated it, which is why e.getSource() can be compared with button.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.