privatestaticclassMyMonitorimplementsActionListener{//build the ActionLister for the north button and the south button ,named myActionListener@OverridepublicvoidactionPerformed(ActionEvent e){//輸入 e. 查看源碼.if(e.getActionCommand()=="north"){
System.out.println("north Button been clicked ,and MyMonitor class run successfully.");}elseif(e.getActionCommand()=="south"){
System.out.println("south Button been clicked ,and MyMonitor class run successfully.");}}}
package GUI.事件監聽;import GUI.MyClass.MySystemExit;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;publicclassTest2兩個按鈕實現同一個監聽 {publicstaticvoidmain(String[] args){
Frame frame =newFrame("Test2兩個按鈕實現同一個監聽");
frame.setVisible(true);
Button north =newButton("north");
Button south =newButton("south");//自定義觸發會顯示的ActionCommand 默認 爲Button("...");中的值.//add listener for the south and north...
north.addActionListener(newMyMonitor());
south.addActionListener(newMyMonitor());//2個按鈕add the same ActionListener
frame.add(north, BorderLayout.NORTH);
frame.add(south, BorderLayout.SOUTH);//l,s,c
frame.setLocation(100,100);
frame.setSize(400,400);
frame.setBackground(newColor(99,255,240));//System.exit(0);newMySystemExit(frame);}privatestaticclassMyMonitorimplementsActionListener{//build the ActionLister for the north button and the south button ,named myActionListener@OverridepublicvoidactionPerformed(ActionEvent e){//輸入 e. 查看源碼.if(e.getActionCommand()=="north"){
System.out.println("north Button been clicked ,and MyMonitor class run successfully.");}elseif(e.getActionCommand()=="south"){
System.out.println("south Button been clicked ,and MyMonitor class run successfully.");}}}}
south Button been clicked ,and MyMonitor class run successfully.
north Button been clicked ,and MyMonitor class run successfully.
south Button been clicked ,and MyMonitor class run successfully.
north Button been clicked ,and MyMonitor class run successfully.