Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

swing - event handling in java and the execution of actionPerformed method in java

I have written a small code in java for simpleGUI.

package guidemo1;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

public class GuiDemo1 implements ActionListener{
 JButton button;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        GuiDemo1 gui=new GuiDemo1();
        gui.go();
    }

    public void go()
    {
        JFrame frame=new JFrame();
        button=new JButton();
        frame.getContentPane().add(button);
        button.addActionListener(this);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);

    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
        button.setText("I've been clicked");
    }
}

I am newbie to JAVA.I have few questions related to this program.

Can some one explain how actionPerformed method gets executed with out any call?

Here I have defined frame object locally to the go() method and we are using button in actionPerformed which is another method.How is that possible?Isn't the button gets embedded on the frame?

Thanks..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Welcome to an event driven environment.

In this environment, you register "listeners" that wait until something happens and then report back to you via a well defined interface structure.

Basically, what's a happening, is you registered yourself as an interested party to action events that may occur on a button. You've done this by implementing the ActionListener interface. This allows the button, when an action is performed to call back to your actionPerformed method at some time in the future.

This is commonly known as an observer pattern.

You might find Writing Event Listeners a useful read


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...