2.2 multi-threaded Swing event processing
To improve its efficiency and reduce its complexity, all Swing components are designed to be non-thread-safe. Although this sounds scary, it simply means that all access to the Swing component needs to be completed by a single thread-the event distribution thread. If we are not sure that we are located in a specific thread, we can use the public static boolean isDispatchThread () method to request the EventQueue class or use the public static boolean isEventDispatchThread () method to request the SwingUtilities class. The latter serves as the proxy of the former.
With the help of the EventQueue class, we can create a Runnable object and execute it on the event distribution thread to access the component correctly. If we need to execute a task on the event distribution thread, but we do not need results or care about when the task is completed, we can use the public static void invokeLater (Runnable runnable) method of EventQueue. In the opposite case, We can inherit our work only when the task ends and the return value is returned. We can use the public static void invokeAndWait (Runnable runnable) method of EventQueue. The code for getting the value should be completed by us, rather than the return value of the invokeAndWait () method.
To demonstrate how to create a Swing-based program, list 2-1 shows the source code of an optional button.
Import javax. swing .*;
Import java. awt .*;
Import java. awt. event .*;
Public class ButtonSample {
Public static void main (String args []) {
Runnable runner = new Runnable (){
Public void run (){
JFrame frame = new JFrame ("Button Sample ");
Frame. setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE );
JButton button = new JButton ("Select Me ");
// Define ActionListener
ActionListener actionListener = new ActionListener (){
Public void actionreceivmed (ActionEvent actionEvent ){
System. out. println ("I was selected .");
}
};
// Attach listeners
Button. addActionListener (actionListener );
Frame. add (button, BorderLayout. SOUTH );
Frame. setSize (300,100 );
Frame. setVisible (true );
}
};
EventQueue. invokeLater (runner );
}
} The buttons generated by the Code are as follows:
First, let's take a look at the invokeLater () method. It needs a Runnable object as a parameter. We create a Runnable object and pass it to the invokeLater () method. After the current event is distributed, the Runnable object is executed.
Runnable runnable = new Runnable (){
Public void run (){
// Do work to be done
}
}
EventQueue. invokeLater (runnable); if we want our Swing GUI creation to be thread-safe, all our Swing code should follow this pattern. To access the command line parameters, you only need to add the final keyword before the parameter Declaration: public static void main (final String args []). This seems to have gone beyond a simple example, but it can ensure the thread security of our program and ensure that access to all Swing components is completed through the event distribution thread. (However, calling repaint (), revalidate (), and invalidate () does not need to be completed through the event distribution thread .)
Another line of code to be interpreted in List 2-1 is
Frame. setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE); by default, if the small X in the title bar of the container shown in Figure 2-3 is not closed, the program will not be closed; on the contrary, the framework will be invisible. Setting the default close operation to JFrame. EXIT_ON_CLOSE allows the program to be closed when the user clicks X. In Chapter 8th, we will learn more about JFrame classes.
2.2.1 use SwingUtilities for mouse button Identification
The Swing component set contains a tool class named SwingUtilities, which provides a set of common help methods. In this book, when the specific methods of this class are combined, we will encounter this class intermittently. For the button example in List 2-1, we are interested in the method related to determining which mouse button to select.
The MouseInputListener interface is composed of seven methods: mouseClick (MouseEvent), mouseEntered (MouseEvent), mouseExited (MouseEvent), mousePressed (MouseEvent), mouserelisted (MouseEvent) in parameters, and MouseMotionListener) and mouseMove (MouseEvent ). If we need to determine which mouse button is selected (or released) when an event occurs, we can check the modifiers attribute of the MouseEvent, compare it with various mask setting constants in the InputEvent class.
For example, to check whether the mouse button is pressed in the mouse press event, we can use the following code in our mouse listener mousePressed () method:
Public void mousePressed (MouseEvent mouseEvent ){
Int modifiers = mouseEvent. getModifiers ();
If (modifiers & InputEvent. BUTTON2_MASK) = InputEvent. BUTTON2_MASK ){
System. out. println ("Middle button pressed .");
}
} Although this method can work well, the SwingUtilities class provides three methods to simplify the process:
SwingUtilities. isLeftMouseButton (MouseEvent mouseEvent)
SwingUtilities. isMiddleMouseButton (MouseEvent mouseEvent)
SwingUtilities. isRightMouseButton (MouseEvent mouseEvent) Now we do not need to manually obtain the identifier and compare it with the mask. We can request SwingUtilities to complete these tasks, as shown below:
If (SwingUtilities. isMiddleMouseButton (mouseEvent )){
System. out. println ("Middle button released .");
} This makes our code easier to read and maintain.
List 2-2 contains an updated ButtonSample, where another listener is added to detect which mouse button is pressed.
/**
*
*/
Package swingstudy. ch02;
Import java. awt. BorderLayout;
Import java. awt. EventQueue;
Import java. awt. event. ActionEvent;
Import java. awt. event. ActionListener;
Import java. awt. event. InputEvent;
Import java. awt. event. MouseAdapter;
Import java. awt. event. MouseEvent;
Import java. awt. event. MouseListener;
Import javax. swing. JButton;
Import javax. swing. JFrame;
Import javax. swing. SwingUtilities;
/**
* @ Author lenovo
*
*/
Public class ButtonSample2 {
/**
* @ Param args
*/
Public static void main (String [] args ){
// TODO Auto-generated method stub
Runnable runner = new Runnable (){
Public void run (){
JFrame frame = new JFrame ("Button Sample ");
Frame. setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE );
JButton button = new JButton ("Select Me ");
ActionListener actionListener = new ActionListener (){
Public void actionreceivmed (ActionEvent event ){
System. out. println ("I was selected ");
}
};
MouseListener mouseListener = new MouseAdapter (){
Public void mousePressed (MouseEvent event ){
Int modifiers = event. getModifiers ();
If (modifiers & InputEvent. button?mask) = InputEvent. button=mask ){
System. out. println ("Left button is pressed ");
}
If (modifiers & InputEvent. BUTTON2_MASK) = InputEvent. BUTTON2_MASK ){
System. out. println ("Middle button is pressed ");
}
If (modifiers & InputEvent. BU