Home | | Web Programming | Event Handling - Swing

Chapter: Java The Complete Reference : Introducing GUI Programming with Swing : Introducing Swing

Event Handling - Swing

The preceding example showed the basic form of a Swing program, but it left out one important part: event handling.

Event Handling

 

The preceding example showed the basic form of a Swing program, but it left out one important part: event handling. Because JLabel does not take input from the user, it does not generate events, so no event handling was needed. However, the other Swing components do respond to user input and the events generated by those interactions need to be handled. Events can also be generated in ways not directly related to user input. For example, an event is generated when a timer goes off. Whatever the case, event handling is a large part of any Swing-based application.

 

The event handling mechanism used by Swing is the same as that used by the AWT. This approach is called the delegation event model, and it is described in Chapter 24. In many cases, Swing uses the same events as does the AWT, and these events are packaged in java.awt.event. Events specific to Swing are stored in javax.swing.event.

Although events are handled in Swing in the same way as they are with the AWT, it is still useful to work through a simple example. The following program handles the event generated by a Swing push button. Sample output is shown in Figure 31-2.


// Handle an event in a Swing program.

 

import java.awt.*; import java.awt.event.*; import javax.swing.*;

 

class EventDemo {

 

JLabel jlab;

 

EventDemo() {

 

// Create a new JFrame container.

 

JFrame jfrm = new JFrame("An Event Example");

 

     //Specify FlowLayout for the layout manager.

     jfrm.setLayout(new FlowLayout());

 

     //Give the frame an initial size.

 

     jfrm.setSize(220, 90);

 

     //Terminate the program when the user closes the application.

 

     jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 

     //Make two buttons.

 

JButton jbtnAlpha = new JButton("Alpha");

 

JButton jbtnBeta = new JButton("Beta");

 

     //Add action listener for Alpha.

     jbtnAlpha.addActionListener(new ActionListener() {

 

public void actionPerformed(ActionEvent ae) { jlab.setText("Alpha was pressed.");

 

}

 

});

 

     //Add action listener for Beta.

     jbtnBeta.addActionListener(new ActionListener() {

 

public void actionPerformed(ActionEvent ae) { jlab.setText("Beta was pressed.");

 

}

 

});

 

     //Add the buttons to the content pane.

     jfrm.add(jbtnAlpha); jfrm.add(jbtnBeta);

 

     //Create a text-based label.

 

jlab = new JLabel("Press a button.");

 

     //Add the label to the content pane.

     jfrm.add(jlab);

 

     //Display the frame.

 

     jfrm.setVisible(true);

 

}

 

public static void main(String args[]) {

 

// Create the frame on the event dispatching thread.

SwingUtilities.invokeLater(new Runnable() {

 

public void run() { new EventDemo();

 

}

 

});

 

}

 

}

 

First, notice that the program now imports both the java.awt and java.awt.event packages. The java.awt package is needed because it contains the FlowLayout class, which supports the standard flow layout manager used to lay out components in a frame. (See Chapter 26 for coverage of layout managers.) The java.awt.event package is needed because it defines the ActionListener interface and the ActionEvent class.

The EventDemo constructor begins by creating a JFrame called jfrm. It then sets the layout manager for the content pane of jfrm to FlowLayout. Recall that, by default, the content pane uses BorderLayout as its layout manager. However, for this example, FlowLayout is more convenient. Notice that FlowLayout is assigned using this statement:

 

jfrm.setLayout(new FlowLayout());

 

As explained, in the past you had to explicitly call getContentPane( ) to set the layout manager for the content pane. This requirement was removed as of JDK 5.

After setting the size and default close operation, EventDemo( ) creates two push buttons, as shown here:

 

JButton jbtnAlpha = new JButton("Alpha");

 

JButton jbtnBeta = new JButton("Beta");

 

The first button will contain the text "Alpha" and the second will contain the text "Beta". Swing push buttons are instances of JButton. JButton supplies several constructors. The one used here is

 

JButton(String msg)

 

The msg parameter specifies the string that will be displayed inside the button.

 

When a push button is pressed, it generates an ActionEvent. Thus, JButton provides the addActionListener( ) method, which is used to add an action listener. (JButton also provides removeActionListener( ) to remove a listener, but this method is not used by the program.) As explained in Chapter 24, the ActionListener interface defines only one method: actionPerformed( ). It is shown again here for your convenience:

 

void actionPerformed(ActionEvent ae)

 

This method is called when a button is pressed. In other words, it is the event handler that is called when a button press event has occurred.

Next, event listeners for the button’s action events are added by the code shown here:

// Add action listener for Alpha.

jbtnAlpha.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent ae) {

jlab.setText("Alpha was pressed.");

 

}

 

});

// Add action listener for Beta.

jbtnBeta.addActionListener(new ActionListener() {

 

public void actionPerformed(ActionEvent ae) { jlab.setText("Beta was pressed.");

 

}

 

});

 

Here, anonymous inner classes are used to provide the event handlers for the two buttons. Each time a button is pressed, the string displayed in jlab is changed to reflect which button was pressed.

 

Beginning with JDK 8, lambda expressions can also be used to implement event handlers. For example, the event handler for the Alpha button could be written like this:

 

jbtnAlpha.addActionListener( (ae) -> jlab.setText("Alpha was pressed."));

 

As you can see, this code is shorter. For the benefit of readers using versions of Java prior to JDK 8, subsequent examples will not use lambda expressions, but you should consider using them for new code that you create.

 

Next, the buttons are added to the content pane of jfrm:

 

jfrm.add(jbtnAlpha);

 

jfrm.add(jbtnBeta);

 

Finally, jlab is added to the content pane and window is made visible. When you run the program, each time you press a button, a message is displayed in the label that indicates which button was pressed.

One last point: Remember that all event handlers, such as actionPerformed( ), are called on the event dispatching thread. Therefore, an event handler must return quickly in order to avoid slowing down the application. If your application needs to do something time consuming as the result of an event, it must use a separate thread.

 


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Java The Complete Reference : Introducing GUI Programming with Swing : Introducing Swing : Event Handling - Swing |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.