A listener object is used to listen to two objects. How can we determine the event source?
Leftright. Java (driver)
Leftrightpanel. Java
Effect
The source program is as follows:
Import javax. Swing. jframe;
Public class leftright {
Public static void main (string [] ARGs ){
Jframe frame = new jframe ("right or left ");
Frame. setdefaclocloseoperation (jframe. exit_on_close );
Frame. getcontentpane (). Add (New leftrightpanel ());
Frame. Pack ();
Frame. setvisible (true );
}
}
Import java. AWT. color;
Import java. AWT. dimension;
Import java. AWT. label;
Import java. AWT. Panel;
Import java. AWT. event. actionevent;
Import java. AWT. event. actionlistener;
Import javax. Swing. jbutton;
Import javax. Swing. jpanel;
Public class leftrightpanel extends panel {
Private jbutton left, right;
Private Label label;
// Define the panel for the bulk button.
Private jpanel buttonpanel;
Public leftrightpanel (){
Left = new jbutton ("Left ");
Right = new jbutton ("right ");
Buttonlistener listener = new buttonlistener ();
Left. addactionlistener (listener );
Right. addactionlistener (listener );
Label = new label ("push a button ");
Buttonpanel = new jpanel ();
Buttonpanel. setpreferredsize (new dimension (200,40 ));
Buttonpanel. setbackground (color. Cyan );
Buttonpanel. Add (left );
Buttonpanel. Add (right );
Setpreferredsize (new dimension (200,80 ));
Setbackground (color. Cyan );
Add (Label );
Add (buttonpanel );
}
// Determine the event Source
Public class buttonlistener implements actionlistener {
Public void actionreceivmed (actionevent e ){
If (E. getsource () = left)
Label. settext ("Left ");
Else
Label. settext ("right ");
}
}
}
The two buttons are placed in the same buttonpanel. This Panel is not represented by the leftrightpanel class. Place the two buttons in the same panel to ensure the relative positional relationship when they are displayed, that is, resetting the framework using various methods is not affected.