How does Java know when a JButton has been pressed?

September 18, 2026 3 answers
Asked by bicycle_lane
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?

Answers

mol+ratio4
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.
Reply to this answer
+5 theorem attempts
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.
Reply to this answer
sun-bleached
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.

8hr_germ: 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.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions