Sorry but this is a concept that I never realized and I never used into my project. I need to learn and use it, absolutly.
So i read many articles about interface and event handling, but it doesnt keep in my mind.
Just start with an easy example :
public class Main implements ActionListener{
JButton but=new JButton("BUTTON");
public Main() {
but.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
// DO SOMETHINGS WHEN THE BUTTON IS CLICKED
}
}
This code is absolutly easy. I implements the ActionListener interface, so i need to write my own code of his method (actionPerformed).
What i dont understand is :
1 – Who implements the addActionListener method? Its not a method on JButton class. Who provides this method?
2 – What is the bridge between the addActionListener and the actionPerformed method? The first should provide the Event e to the second… and both must be implemented somewhere…
Sorry for this question. I try to learn this (by reading many articles on internet) but i can’t understand how this can work!
Cheers and thanks to everybody 🙂
JButton extends AbstractButton, inheriting the addActionListener from it.
In simplified terms: when particular area on screen is pressed, AWT event handler thread notifies the UI element located at that area of the screen.
In our case, if the UI element is the button, the button event handling logic loops over the list of action listeners (registered through "addActionListener") and calls "actionPerformed" method in each listener.
See How to Use Buttons, Check Boxes, and Radio Buttons in The Java Tutorial for information and examples of using buttons.