I just started learning GUI with Swing and don't exactly understand how the actionPerformed
method works. Consider the following code:
//code to create a button and change its text when clicked
public class simplegui implements ActionListener {
JButton button;
public static void main(String[] args) {
simplegui gui=new simplegui();
gui.go();
}
public void go() {
JFrame frame=new Frame();
button=new JButton("click Me");
button.addActionListener(this);
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
button.setText("I've been clicked!");
}
}
Shouldn't an object be created for a class before a method on it is evoked (except for static methods)?
When the button is clicked the actionPerformed
method is called, but how? Where is the call made? I've implemented the interface ActionListener
, but where is the code that knows that when an action occurs the 'ActionEvent' Object should be sent to the 'actionPerformed' method? Is it present in the Button class? Is the addActionListener
method present in the Button class?
When I click the button, how is the system call action performed and where is the code that executes gui.actionPerformed()
?
I followed Java concepts of OO, static etc. until now but this whole event driven programming is confusing.