Java Event Monitoring
//Event Monitoring//Event monitoring, wrote a small case, click the button to change the color of the Panel. Importjava.awt.*;Importjavax.swing.*;Importjava.awt.event.*; public classIndexextendsJFrameImplementsactionlistener{//Setup PanelWDMB WDMB =NewWDMB (); //Set ButtonJButton ANNIU1 =NewJButton ("yellow"); JButton ANNIU2=NewJButton ("red"); public Static voidMain (string[] Args)throwsexception{//instantiate the current classIndex index =NewIndex (); } //Automatic Execution publicIndex () {//set the background color of the panelWdmb.setbackground (color.yellow); //Add to Interface this. Add (anniu1,borderlayout.north); this. Add (anniu2,borderlayout.south); this. Add (wdmb); //Adding listener EventsAnniu1.addactionlistener ( this); Anniu1.setactioncommand ("1");//Difference button Identification codeAnniu2.addactionlistener ( this); Anniu2.setactioncommand ("2");//Difference button Identification code this. setSize (500,500); this. setlocation (300,200); this. Settitle ("drawing"); this. Setdefaultcloseoperation (jframe.exit_on_close); this. setvisible (true); } //abstract methods of ActionListener//ActionEvent e is Fixed. public voidactionperformed (actionevent E) {//e.getactioncommand (). equals ("1") determines if the "difference button identifier" is equal if(e.getactioncommand (). equals ("1") {System.out.println ("yellow Button pressed"); Wdmb.setbackground (color.yellow); } if(e.getactioncommand (). equals ("2") {System.out.println ("red Button pressed"); Wdmb.setbackground (color.red); } } }//Panel MethodclassWdmbextendsjpanel{//method Overrides//JPanel the method, the following format is fixed//paint is automatically called in three cases//1, Start the program 2, the window size changes 3, when running the repaint function public voidpaint (Graphics G) {//methods that override the parent class Super. Paint (g); }}
Java Event Listener-controls