Comparison of Three event handling methods in Java swing)

Source: Internet
Author: User

From http://tech.ddvip.com/2006-04/11438293201794.html

Swing is an indispensable tool group in Java and a powerful tool for creating graphical user interface (GUI) programs. The Java Swing component automatically generates various events to respond to user behavior. For example, when you click a button or select a menu item, the Swing component generates an ActionEvent. The Swing component generates many events, such as ActionEvents, ChangeEvents, and ItemEvents, to respond to users' mouse clicks, change of the value in the list box, and start timer. In Java Swing programming, by registering a listener, we can listen to events generated by the event source to process the user behavior we need to process in the event handler.

The general steps for processing component events in Java Swing are as follows:

1. Create a new component (such as JButton ).

2. Add the component to the corresponding panel (such as JPanel ).

3. register the listener to listen for events generated by the event source (for example, responding to the user clicking the button through ActionListener ).

4. Define Method (For example, define the corresponding method in actionreceivmed of actionlistener ).

The above steps can be implemented in multiple ways. But people usually use two methods. The first method is to use only one listener and multiple if statements to determine which component generates events. The second method is to use multiple internal classes to respond to various events generated by different components, the specific implementation is divided into two methods: one is anonymous internal class and the other is general internal class.

To illustrate how to use the above three methods to handle events, we have established a simple application. The program interface has two buttons (see figure 1). When you click the corresponding button, a dialog box will pop up showing the corresponding content (see figure 2 ). With this simple program, you can implement more and more complex User Interface programs.

Figure 1

Figure 2

First, we use a single listener to implement this program. We define a class named Simple1 to include all the code. All user actions (such as clicking a button) are performed by actionreceivmed in the SimpleListenner of a listener. Method . The following code is used:

  /*
* Simple1.java-first method for event processing
* In this example, an actionlistener is used to listen to events generated by the event source.
* Use some if statements to determine the event source.
*/

Import java. AWT .*;
Import java. AWT. event .*;
Import javax. Swing .*;
Public class simple1
{
Private Static jframe frame; // It is defined as a static variable for main to use.
Private Static jpanel mypanel; // This panel is used to place button Components
Private jbutton button1; // define the button component here
Private JButton button2; // used by the ActionListener
Public Simple1 () // constructor to create a graphical interface
{
// Create a panel
MyPanel = new JPanel ();
// Create button
Button1 = new JButton ("button 1"); // create button 1
Button2 = new JButton ("button 2 ");
SimpleListener ourListener = new SimpleListener ();
// Create an actionlistener to share the two buttons
Button1.addActionListener (ourListener );
Button2.addActionListener (ourListener );
MyPanel. add (button1); // add button to panel
MyPanel. add (button2 );
}
Private class SimpleListener implements ActionListener
{
/*
* Use this internal class to listen to events generated by all event sources
* Easy to process Event code Modularization
*/
Public void actionreceivmed (ActionEvent e)
{
// Get the button name using getActionCommand
// You can also use getSource () to implement
// 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 ");
Else
JOptionPane. showMessageDialog (frame,
"Unknown event ");
}
}
Public static void main (String s [])
{
Simple1 gui = new Simple1 (); // create a Simple1 component
    
Frame = new JFrame ("Simple1"); // create a JFrame
// The usual method for processing the Close event
Frame. addWindowListener (new WindowAdapter (){
Public void windowClosing (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 main Method , We define a JFrame, and then add the Panel Jpanel to the form. The Panel contains two buttons. The corresponding variables Frame, button1, and button2 are defined at the beginning of the program.

In the main method of the program entry, create the Simple1 component, create a user GUI through the constructor, define a panel Jpanle, add two buttons, and then use JButton. addActionListerner adds the two buttons to an activity listener SimpleLister. Finally, the two buttons are added to the Panel. After the GUI is created, we add the panel to the form and display the result. When you click the button, the program calls the actionreceivmed method, uses 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 complicated, a large string of if statements are required, and the program code is difficult to read and maintain. Of course, if the number of events to be processed is small, this method is relatively simple.

Using anonymous internal classes can solve the above problems. Use a simple anonymous internal class as the variable of addActionListener. The following is the implementation code:

  /*
* Simple2.java-method 2 for event processing
* In this example, an anonymous internal class is used to listen to events generated by each event source.
* Avoid using some if statements to determine the event source.
*/
Import java. awt .*;
Import java. awt. event .*;
Import javax. swing .*;
Public class Simple2
{
Private static JFrame frame; // It is defined as a static variable for main to use.
Private static JPanel myPanel; // This panel is used to place button Components
Private JButton button1; // define the button component here
Private jbutton button2; // used by the actionlistener
  
Public simple2 () // constructor to create a graphical interface
{
// Create a panel
Mypanel = new jpanel ();
// Create button
Button1 = new jbutton ("button 1"); // create button 1
Button2 = new jbutton ("button 2 ");
// Each event source requires a listener
// Define an anonymous internal class to listen to events generated by the event Source
Button1.addactionlistener (
New actionlistener ()
{
Public void actionreceivmed (actionevent E)
{
Joptionpane. showmessagedialog (frame,
"Button 1 is clicked ");
}
}
);
Button2.addactionlistener (
New actionlistener ()
{
Public void actionreceivmed (ActionEvent e)
{
JOptionPane. showMessageDialog (frame,
"Button 2 is clicked ");
}
}
);
MyPanel. add (button1); // add button to panel
MyPanel. add (button2 );
}
Public static void main (String s [])
{
Simple2 gui = new Simple2 (); // create a Simple2 component
    
Frame = new JFrame ("Simple2"); // create a JFrame
// The usual method for processing the Close event
Frame. addWindowListener (new WindowAdapter (){
Public void windowClosing (WindowEvent e)
{System. exit (0 );}});
Frame. getContentPane (). add (myPanel );
Frame. pack ();
Frame. setVisible (true );
}
}

Using anonymous internal classes also has many other problems. First, according to the different positions defined by the component in the Code, the definition of the class and the Code for processing the event will be scattered in all parts of the program, not in one piece, it is also not easy to read and maintain. All events are handled by nested blocks, making it difficult to visually locate the program code. If the event processing program is complex, the code in the internal class will become long and you cannot find the corresponding component definition location. Finally, when the toolbar, menu bar, and so on need to process the same user behavior Method It makes the code more difficult to maintain.

The general naming internal class can solve the above problems. All event handling methods are centralized and have meaningful names, so the program can be easily read and maintained. A single event handler can also be reused by the toolbar, menu bar, and so on,

The following is the implementation code:

  /*
* Simple3.java-method 3 for event processing
* For this example, we will use inner member classes
* In this example, a general internal class is used to listen to events generated by each event source.
* This method avoids code confusion caused by the use of anonymous internal classes in the second method.
* Easy to centrally process Event code
* Each hander can be used multiple times by the toolbar or menu.
*/
Import java. AWT .*;
Import java. AWT. event .*;
Import javax. Swing .*;
Public class simple3
{
Private Static jframe frame; // It is defined as a static variable for main to use.
Private Static jpanel mypanel; // This panel is used to place button Components
Private jbutton button1; // define the button component here
Private jbutton button2; // used by the actionlistener
    
// Use a general internal class to listen to events generated by each event source, such as (button1, button2)
Private class button1handler implements actionlistener
{
Public void actionreceivmed (ActionEvent e)
{
JOptionPane. showMessageDialog (frame,
"Button 1 is clicked ");
}
}
  
Private class Button2Handler implements ActionListener
{
Public void actionreceivmed (ActionEvent e)
{
JOptionPane. showMessageDialog (frame,
"Button 2 is clicked ");
}
}
  
Public Simple3 () /// constructor to create a graphical interface
{
// Create a panel
MyPanel = new JPanel ();
// Create button
Button1 = new JButton ("button 1"); // create button 1
Button2 = new JButton ("button 2 ");
// Register and listen to internal classes for each component
Button1.addActionListener (new Button1Handler ());
Button2.addActionListener (new Button2Handler ());
MyPanel. add (button1); // add button to panel
MyPanel. add (button2 );
}
Public static void main (String s [])
{
Simple3 gui = new Simple3 (); // create a Simple3 component
Frame = new JFrame ("Simple3"); // create a JFrame
// The usual method for processing the Close event
Frame. addWindowListener (new WindowAdapter (){
Public void windowClosing (WindowEvent e)
{System. exit (0 );}});
Frame. getContentPane (). add (myPanel );
Frame. pack ();
Frame. setVisible (true );
}
}

 

The above analyzes the three event handling methods in Java swing, which are implemented using general internal classes. From the perspective of code writing, reading, maintenance, and program scalability, it is most recommended for use.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.