Swing is an indispensable window tool group in Java and a powerful tool for users to build graphical user interface (GUI) programs. The Java swing component automatically generates various events to respond to user behavior. The swing component generates a actionevent when the user taps a button or selects a menu item. Swing components generate a number of events, such as Actionevents,changeevents,itemevents, to respond to a user's mouse-click behavior, changes in the value of a list box, and the start of a timer. In Java Swing programming, by registering the listener, we can listen to events generated by the event source to handle the user behavior we need to handle in the event handler.
The general steps for handling individual component events in Java swing are:
1. Create a new component (such as JButton).
2. Add the component to the appropriate panel (for example, JPanel).
3. Registers the listener to listen for events generated by the event source (for example, by ActionListener to respond to user click buttons).
4. Defines the method that handles the event, such as defining the appropriate method in actionperformed in ActionListener.
The above steps can be implemented in a variety of ways. But people usually use two different methods. The first approach is to use only one listener and multiple if statements to determine which component generated the event, and the second is to use multiple internal classes to respond to various events produced by different components in two ways, one for anonymous inner classes and one for general internal classes.
To illustrate how to use the above three methods to implement event handling, we build a simple application. The program interface has two buttons, when the user clicks the corresponding button, a dialog will pop up to display the corresponding content. With this simple program, you can implement your own more, more complex user interface programs.
First, we use a single listener to implement the program. We define a class named Simple1 to include all the code. All user behavior, such as clicking a button, is handled by the Actionperformed method in a listener Simplelistenner. Here's the code:
/*** Simple1.java-the first method of handling an event * In this example, use a actionlistener to listen to events generated by the event source * Use some if statements to determine which event source*/ Importjava.awt.*; Importjava.awt.event.*; Importjavax.swing.*; Public classSimple1 {Private StaticJFrame frame;//defined as a static variable so that main uses Private StaticJPanel Mypanel;//The panel is used to place the button assembly PrivateJButton button1;//Define button Components here PrivateJButton button2;//for ActionListener to use PublicSimple1 ()//constructor, creating a graphical interface{//New PanelMypanel =NewJPanel (); //New ButtonButton1 =NewJButton ("button 1");//New Button 1Button2 =NewJButton ("button 2"); SimpleListener Ourlistener=NewSimpleListener (); //Create a ActionListener to let two buttons shareButton1.addactionlistener (Ourlistener); Button2.addactionlistener (Ourlistener); Mypanel.add (button1); //Add a button to a panelMypanel.add (button2); }Private classSimpleListenerImplementsActionListener {/*** Use this inner class to listen for events generated by all event sources * Easy to handle event code modularity*/ Public voidactionperformed (ActionEvent e) {//get button names with Getactioncommand//You can also use GetSource () to achieve//if (E.getsource () ==button1)String ButtonName=E.getactioncommand (); if(Buttonname.equals ("button 1")) Joptionpane.showmessagedialog (frame,"Button 1 is clicked"); Else if(Buttonname.equals ("button 2")) Joptionpane.showmessagedialog (frame,"Button 2 is clicked"); ElseJoptionpane.showmessagedialog (frame,"Unknown Event" ); }} Public Static voidMain (String s[]) {Simple1 GUI=NewSimple1 ();//New Simple1 ComponentFrame=NewJFrame ("Simple1");//New JFrame//common ways to handle shutdown eventsFrame.addwindowlistener (NewWindowadapter () { Public voidwindowclosing (windowevent e) {system.exit (0);} }); Frame.getcontentpane (). Add (Mypanel); Frame.pack (); Frame.setvisible (true); }}
Let's take a look at how the above code works. In the main method, we define a jframe and then add the panel JPanel to the form, which includes two buttons. The corresponding variable frame,button1,button2 is defined at the beginning of the program.
In the program entrance Main method, first create a new Simple1 component, build the user GUI through the constructor, define a panel Jpanle, add two buttons, and then use Jbutton.addactionlisterner adds two buttons to an active listener simplelister, and finally two buttons to the panel. When the GUI is established, we add the Panel to the form and display the results. When the user taps the button, the program calls the Actionperformed method, using the IF statement to determine which button is clicked, and then displays the corresponding content in the dialog box.
The disadvantage of using a listener to handle events is that when the program is complex, it requires a large number of if statements to be implemented, and the program code is difficult to read and maintain. Of course, this is a simpler approach if you are dealing with fewer events.
The above problems can be resolved by using anonymous inner classes. Use the simple anonymous inner class as a addActionListener variable. Here is the implementation code:
/*** Simple2.java-the second method of handling events * In this example, an anonymous inner class is used to listen for events generated by each event source * Avoid using some if statements to determine which event source*/ Importjava.awt.*; Importjava.awt.event.*; Importjavax.swing.*; Public classSimple2 {Private StaticJFrame frame;//defined as a static variable so that main uses Private StaticJPanel Mypanel;//The panel is used to place the button assembly PrivateJButton button1;//Define button Components here PrivateJButton button2;//for ActionListener to use PublicSimple2 ()//constructor, creating a graphical interface{//New PanelMypanel =NewJPanel (); //New ButtonButton1 =NewJButton ("button 1");//New Button 1Button2 =NewJButton ("button 2"); //Each event source requires a listener//define an anonymous inner class to listen for events generated by the event sourceButton1.addactionlistener (NewActionListener () { Public voidactionperformed (ActionEvent e) {Joptionpane.showmessagedialog (frame,"Button 1 is clicked"); } } ); Button2.addactionlistener (NewActionListener () { Public voidactionperformed (ActionEvent e) {Joptionpane.showmessagedialog (frame,"Button 2 is clicked"); } } ); Mypanel.add (button1); //Add a button to a panelMypanel.add (button2); } Public Static voidMain (String s[]) {Simple2 GUI=NewSimple2 ();//New Simple2 ComponentFrame=NewJFrame ("Simple2");//New JFrame//common ways to handle shutdown eventsFrame.addwindowlistener (NewWindowadapter () { Public voidwindowclosing (windowevent e) {system.exit (0);} }); Frame.getcontentpane (). Add (Mypanel); Frame.pack (); Frame.setvisible (true); }}
The use of anonymous inner classes also has many additional problems. First, depending on where the component is defined in the code, the definition of the class and the code that handles the event will be scattered over the parts of the program, not in one piece, and also not easy to read and maintain. Each event is handled by a nested block of blocks, which visually makes it difficult to locate the program code. If the event handler is complex, the code in the inner class will become very long and you will not find the corresponding component definition location. Finally, this approach makes the code more difficult to maintain when the same user behavior needs to be handled, such as toolbars, menu columns, and so on.
We can solve many of these problems by using generic named inner classes. All event handling methods are focused on one piece, and all have meaningful names, and the program is very easy to read and maintain. A single event handler can also be reused with toolbars, menu bars, and so on.
Here is the implementation code:
/*** Simple3.java-the third method of handling events * For this example, we'll use inner member classes to * in this example, the general inner class is used to listen for events generated by each event source * This method avoids code clutter caused by the use of anonymous inner classes in the second method * facilitates centralized processing of event code * each hander can be used multiple times by a toolbar or menu*/ Importjava.awt.*; Importjava.awt.event.*; Importjavax.swing.*; Public classSimple3 {Private StaticJFrame frame;//defined as a static variable so that main uses Private StaticJPanel Mypanel;//The panel is used to place the button assembly PrivateJButton button1;//Define button Components here PrivateJButton button2;//for ActionListener to use//use a generic inner class to listen for events generated by each event source (button1, Button2) Private classButton1handlerImplementsActionListener { Public voidactionperformed (ActionEvent e) {Joptionpane.showmessagedialog (frame,"Button 1 is clicked"); }}Private classButton2handlerImplementsActionListener { Public voidactionperformed (ActionEvent e) {Joptionpane.showmessagedialog (frame,"Button 2 is clicked"); }} PublicSimple3 ()// //constructor, creating a graphical interface{//New PanelMypanel =NewJPanel (); //New ButtonButton1 =NewJButton ("button 1");//New Button 1Button2 =NewJButton ("button 2"); //Register listener internal classes for each componentButton1.addactionlistener (NewButton1handler ()); Button2.addactionlistener (NewButton2handler ()); Mypanel.add (button1); //Add a button to a panelMypanel.add (button2); } Public Static voidMain (String s[]) {Simple3 GUI=NewSimple3 ();//New Simple3 ComponentFrame=NewJFrame ("Simple3");//New JFrame//common ways to handle shutdown eventsFrame.addwindowlistener (NewWindowadapter () { Public voidwindowclosing (windowevent e) {system.exit (0);} }); Frame.getcontentpane (). Add (Mypanel); Frame.pack (); Frame.setvisible (true); }}
Three ways to implement ActionListener