I. Overview
The Java AWT is observer mode, and now uses Java to simulate the operation mechanism of the button in AWT.
Second, the Code
1.test.java
1 ImportJava.text.DateFormat;2 ImportJava.text.SimpleDateFormat;3 Importjava.util.ArrayList;4 Importjava.util.Date;5 Importjava.util.List;6 7 Public classTest {8 9 Public Static voidMain (string[] args) {TenButton B =NewButton (); OneB.addactionlistener (NewMyActionListener1 ()); AB.addactionlistener (NewMyActionListener2 ()); - b.buttonpress (); - } the } - - classButton { - + //Store listener with list - PrivateList<actionlistener> actionlisteners =NewArraylist<actionlistener>(); + A Public voidaddActionListener (ActionListener l) { at Actionlisteners.add (l); - } - - Public voidButtonPress () { -ActionEvent e =NewActionEvent (System.currenttimemillis (), This); - for(ActionListener l:actionlisteners) { in l.actionperformed (e); - } to } + } - the InterfaceActionListener { * Public voidactionperformed (ActionEvent e); $ }Panax Notoginseng - classMyActionListener1ImplementsActionListener { the + @Override A Public voidactionperformed (ActionEvent e) { theSystem.out.println ("MyActionListener1"); +System.out.println ("Event Occurrence Time:" +e.gettime () + "event Source:" +E.getsource ()); - } $ $ } - - classMyActionListener2ImplementsActionListener { the - @OverrideWuyi Public voidactionperformed (ActionEvent e) { theSystem.out.println ("MyActionListener2"); -System.out.println ("Event Occurrence Time:" +e.gettime () + "event Source:" +E.getsource ()); Wu - } About $ } - - classActionEvent { - A Private LongTime ; + PrivateObject Source; the - PublicActionEvent (LongTime , Object source) { $ This. Time =Time ; the This. Source =Source; the } the the PublicObject GetSource () { - returnSource; in } the the PublicString GetTime () { About //DateFormat df = new SimpleDateFormat ("Dd:MM:yy:HH:mm:ss"); theDateFormat DF =NewSimpleDateFormat ("Yyyy:MM:dd---HH:mm:ss"); the returnDf.format (NewDate (time)); the } + - the}
Iii. Results of operation
Java analog AWT Button Observer mode