Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the event handling methods in Java Swing

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail what are the event handling methods in Java Swing. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Swing is an indispensable window tool group in Java at present, and it is a powerful tool for users to build graphical user interface (GUI) programs. The Java Swing component automatically generates various events in response to user behavior. For example, when a user clicks a button or selects a menu item, the Swing component generates an ActionEvent. The Swing component generates many events, such as ActionEvents,ChangeEvents,ItemEvents, etc., in response to the user's mouse click behavior, the change of the value in the list box, the start of the timer, and so on. In Java Swing programming, by registering listeners, we can listen to events generated by event sources, thus handling 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 (such as JPanel).

3. Register the listener to listen for events generated by the event source (such as responding to user button clicks through ActionListener).

4. Define methods to handle events (such as defining corresponding methods in actionPerformed in ActionListener).

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

To illustrate how to use the above three methods to implement event handling, let's build a simple application. The program interface has two buttons, and when the user clicks the corresponding button, a dialog box will pop up to display the corresponding content. Through this simple program, you can implement more and more complex user interface programs.

First, we use a single listener to implement the program. We define a class called Simple1 to include all the code. All user behaviors, such as button clicks, are handled by the actionPerformed method in a listener SimpleListenner. Here is the code:

/ *

* Simple1.java-the first way to handle events

* in this example, an ActionListener is used to listen for events generated by the event source

* use some if statements to determine which event source

, /

Import java.awt.*

Import java.awt.event.*

Import javax.swing.*

Public class Simple1

{

Private static JFrame frame; / / 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; / / Button components are defined here

Private JButton button2; / / for ActionListener to use

Public Simple1 () / / constructor to create a graphical interface

{

/ / create a new panel

MyPanel = new JPanel ()

/ / New button

Button1 = new JButton ("Button 1"); / / New Button 1

Button2 = new JButton ("Button 2")

SimpleListener ourListener = new SimpleListener ()

/ / create an actionlistener for the two buttons to share

Button1.addActionListener (ourListener)

Button2.addActionListener (ourListener)

MyPanel.add (button1); / / add buttons to the panel

MyPanel.add (button2)

}

Private class SimpleListener implements ActionListener

{

/ *

* use this inner class to listen for events generated by all event sources

* easy to handle event code modularization

, /

Public void actionPerformed (ActionEvent e)

{

/ / use getActionCommand to get the button name

/ / 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 (); / / New Simple1 component

Frame = new JFrame ("Simple1"); / / New JFrame

/ / the usual method of handling shutdown events

Frame.addWindowListener (new WindowAdapter () {

Public void windowClosing (WindowEvent e)

{System.exit (0);}})

Frame.getContentPane () add (myPanel)

Frame.pack ()

Frame.setVisible (true)

}

}

Let's see 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 entry main method, first create a new Simple1 component, create a user GUI through the constructor, define a panel Jpanle, and add two buttons, then use JButton.addActionListerner to add two buttons to an active listener SimpleLister, and finally, add two buttons to the panel. When the GUI is established, we add the panel to the form and display the results. When the user clicks the button, the program calls the actionPerformed method, determines which button is clicked through the if statement, and then displays the corresponding content in the dialog box.

The disadvantage of using a listener to deal with events is that when the program is more complex, it needs a long string of if statements to implement, and the program code is difficult to read and maintain. Of course, this approach is simpler if you deal with fewer events.

The above problems can be solved by using anonymous inner classes. Use a simple anonymous inner class as a variable to addActionListener. The following is the implementation code:

/ *

* Simple2.java-the second way to handle events

* in this example, anonymous inner classes are used to listen for events generated by each event source

* avoid using if statements to determine which event source

, /

Import java.awt.*

Import java.awt.event.*

Import javax.swing.*

Public class Simple2

{

Private static JFrame frame; / / 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; / / Button components are defined here

Private JButton button2; / / for ActionListener to use

Public Simple2 () / / constructor to create a graphical interface

{

/ / create a new panel

MyPanel = new JPanel ()

/ / New button

Button1 = new JButton ("Button 1"); / / New Button 1

Button2 = new JButton ("Button 2")

/ / each event source needs a listener.

/ / define an anonymous inner class to listen for events generated by event sources

Button1.addActionListener (

New ActionListener ()

{

Public void actionPerformed (ActionEvent e)

{

JOptionPane.showMessageDialog (frame

"Button 1 is clicked")

}

}

);

Button2.addActionListener (

New ActionListener ()

{

Public void actionPerformed (ActionEvent e)

{

JOptionPane.showMessageDialog (frame

"Button 2 is clicked")

}

}

);

MyPanel.add (button1); / / add buttons to the panel

MyPanel.add (button2)

}

Public static void main (String s [])

{

Simple2 gui = new Simple2 (); / / New Simple2 component

Frame = new JFrame ("Simple2"); / / New JFrame

/ / the usual method of handling shutdown events

Frame.addWindowListener (new WindowAdapter () {

Public void windowClosing (WindowEvent e)

{System.exit (0);}})

Frame.getContentPane () add (myPanel)

Frame.pack ()

Frame.setVisible (true)

}

}

There are also many other problems with using anonymous inner classes. First of all, according to the different locations where the components are defined in the code, the definition of the class and the code for handling events will be scattered in all parts of the program, not centralized, and also not easy to read and maintain. The processing of each event is made up of nested program blocks, so it is difficult to locate the program code visually. 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 toolbars, menu bars, and so on need to deal with the same user behavior.

We can solve many of these problems by using generic named inner classes. All the event handling methods are centralized and have meaningful names, and the program is very easy to read and maintain. Individual event handlers can also be reused by toolbars, menu bars, etc.

The following is the implementation code:

/ *

* Simple3.java-the third way to handle events

* For this example, we will use inner member classes to

* in this example, general inner classes are used to listen for events generated by each event source

* this method avoids code confusion caused by the use of anonymous inner classes in the second method

* facilitate centralized processing of event codes

* each Hander can be used multiple times by toolbars or menus

, /

Import java.awt.*

Import java.awt.event.*

Import javax.swing.*

Public class Simple3

{

Private static JFrame frame; / / 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; / / Button components are defined here

Private JButton button2; / / for ActionListener to use

/ / use general inner classes to listen for events generated by each event source, such as (button1, button2)

Private class Button1Handler implements ActionListener

{

Public void actionPerformed (ActionEvent e)

{

JOptionPane.showMessageDialog (frame

"Button 1 is clicked")

}

}

Private class Button2Handler implements ActionListener

{

Public void actionPerformed (ActionEvent e)

{

JOptionPane.showMessageDialog (frame

"Button 2 is clicked")

}

}

Public Simple3 () / constructor to create a graphical interface

{

/ / create a new panel

MyPanel = new JPanel ()

/ / New button

Button1 = new JButton ("Button 1"); / / New Button 1

Button2 = new JButton ("Button 2")

/ / one pair of each component registers to listen on the inner class

Button1.addActionListener (new Button1Handler ())

Button2.addActionListener (new Button2Handler ())

MyPanel.add (button1); / / add buttons to the panel

MyPanel.add (button2)

}

Public static void main (String s [])

{

Simple3 gui = new Simple3 (); / / New Simple3 component

Frame = new JFrame ("Simple3"); / / New JFrame

/ / the usual method of handling shutdown events

Frame.addWindowListener (new WindowAdapter () {

Public void windowClosing (WindowEvent e)

{System.exit (0);}})

Frame.getContentPane () add (myPanel)

Frame.pack ()

Frame.setVisible (true)

}

}

This is the end of this article on "what are the event handling methods in Java Swing". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report