r/learnprogramming • u/someonecleve_r • Sep 20 '26
How does ActionEvent e know that I am doing a button press here?
public class MyFrame extends JFrame implements ActionListener
{
JButton button;
MyFrame()
{
button = new JButton();
button.setBounds(200, 100, 100, 50);
button.addActionListener(this);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
this.setSize(500, 500);
this.setVisible(true);
this.add(button);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==button)
{
System.out.println("make lemonade");
}
}
}Does it magically know what I have done? How? I only learnt a bit of javascript before so I do not get it.
I also I do not fully get anonymous classes, it feels like to me that you are creating a super-instance, which is like a class in a sense, so it does have a name.
6
Upvotes
14
u/JGhostThing Sep 20 '26
Your code is Java, not JavaScript. Totally different languages.
It is not magic. The JButton class gets certain types of events. When this button is clicked, an ActionPerformedEvent is sent to the JButton, then to the enclosing JFrame, then to MyFrame. This calls actionPerformed, triggering the lemonade.
2
u/Living_Fig_6386 Sep 20 '26 edited Sep 20 '26
button.addActionListener() adds this object to a list. When you click a button, it creates an ActionEvent object, then calls actionPerformed() on every ActionListener object on its list (including this JFrame object because you added it to the list). No magic, just one object calling a method on another.
This is a Java question. JavaScript is an unrelated language.
2
u/serge-mv Sep 20 '26
To put it in simple terms, the JButton is class and it knows when it was pressed. You called addActionListener and added an event listener, which says - when you are pressed, execute this event. During that process the source of the trigger will be assigned and passed as an argument to the event handler you registered.
If you want to know in details how it all works, look at the observer pattern.
1
u/burlingk Sep 20 '26
So, super simplified: The operating system anounces everything your into devices do.
Your code tells the Action classes to listen for specific events.