swing - event handling in java and the execution of actionPerformed method in java -
i have written little code in java 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 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 newbie java.i have few questions related program.
can 1 explain how actionperformed method gets executed out call?
here have defined frame object locally go() method , using button in actionperformed method.how possible?isn't button gets embedded on frame?
thanks..
can 1 explain how actionperformed method gets executed out call?
the gui framework swing runs action handling code in background. whenever button pressed or user interacts gui in other way, swing notify application through 1 of many listener
interfaces. in order receive these events, class needs implement proper listener
interface , registered listener on each component interested in.
your class implements actionlistener
interface , calls addactionlistener
register button. when button clicked, swing effort notify registered actionlistener
s calling actionperformed
method. that's how "magic" happens.
here have defined frame object locally go() method , using button in actionperformed method.how possible?isn't button gets embedded on frame?
you add
button frame's content pane - puts button within frame in layout, not in code. because declare button
instance variable putting jbutton button;
outside method, still accessible (non-static
) method in class.
java swing user-interface event-handling
No comments:
Post a Comment