Handling User Events

When a user event is generated by a component that has a listener, a method is called automatically. The method must be found in the class specified when the listener was attached to the component.

Each listener has different methods that are called to receive their events. The ActionListener interface sends events to a method called actionPerformed(). The following is a short example of an actionPerformed() method:

public void actionPerformed(ActionEvent event) {
    // method goes here
}

All action events sent in the program go to this method. If only one component in a program can possibly send action events, you can put statements in this method to handle the event. If more than one component can send these events, you need to check the object sent to the method.

An ActionEvent object is sent to the actionPerformed() method. Several different classes of objects represent the user events that can be sent in a program. These classes have methods to determine which component caused the event to happen. In the actionPerformed() method, if the ActionEvent object is named event, you can identify the component with the following statement:

String cmd = event.getActionCommand();

The getActionCommand() method sends back a string. If the component is a button, the string is the label on the button. If it’s a text field, the string is the text entered in the field. The getSource() method sends back the object that caused the event.

You could use the following actionPerformed() method to receive events from three components: a JButton object called start, a JTextField called speed, and another JTextField called viscosity:

public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();
    if (source == speed) {
        // speed field caused event
    } else if (source == viscosity) {
        // viscosity caused event
    } else {
        // start caused event
    }
}

You can call the getSource() method on all user events to identify the specific object that caused the event.

Check Box and Combo Box Events

Combo boxes and check boxes require the ItemListener interface. Call the component’s addItemListener() method to make it generate these events. The following statements create a check box called superSize that sends out user events when selected or deselected:

JCheckBox superSize = new JCheckBox("Super Size", true);
superSize.addItemListener(this);

These events are received by the itemStateChanged() method, which takes an ItemEvent object as an argument. To see which object caused the event, you can call the event object’s getItem() method.

To determine whether a check box is selected or deselected, compare the value returned by the getStateChange() method to the constants ItemEvent.SELECTED and ItemEvent.DESELECTED. The following code is an example for an ItemEvent object called item:

int status = item.getStateChange();
if (status == ItemEvent.SELECTED) {
    // item was selected
}

To determine the value selected in a JComboBox object, use getItem() and convert that value to a string, as in the following:

Object which = item.getItem();
String answer = which.toString();

Keyboard Events

When a program must react immediately once a key is pressed, it uses keyboard events and the KeyListener interface.

The first step is to register the component that receives key presses by calling its addKeyListener() method. The argument of the method should be the object that implements the KeyListener interface. If it is the current class, use this as the argument.

An object that handles keyboard events must implement three methods:

void keyPressed(KeyEvent)— A method called the moment a key is pressed

void keyReleased(KeyEvent)—A method called the moment a key is released

void keyTyped(KeyEvent)—A method called after a key has been pressed and released

Each of these has a KeyEvent object as an argument, which has methods to call to find out more about the event. Call the getKeyChar() method to find out which key was pressed. This key is returned as a char value, and it only can be used with letters, numbers, and punctuation.

To monitor any key on the keyboard, including Enter, Home, Page Up, and Page Down, you can call getKeyCode() instead. This method returns an integer value representing the key. You then can call getKeyText() with that integer as an argument to receive a String object containing the name of the key (such as Home, F1, and so on).

Listing 15.1 contains a Java application that draws the most recently pressed key in a label by using the getKeyChar() method. The application implements the KeyListener interface, so there are keyTyped(), keyPressed(), and keyReleased() methods in the class. The only one of these that does anything is keyTyped() in Lines 22–25. Create a new Java file called KeyViewer, enter the listing in NetBeans’ source editor, and save the file.

Listing 15.1. The Full Text of KeyViewer.java


 1: import javax.swing.*;
 2: import java.awt.event.*;
 3: import java.awt.*;
 4:
 5: public class KeyViewer extends JFrame implements KeyListener {
 6:     JTextField keyText = new JTextField(80);
 7:     JLabel keyLabel = new JLabel("Press any key in the text field.");
 8:
 9:     KeyViewer() {
10:         super("KeyViewer");
11:         setLookAndFeel();
12:         setSize(350, 100);
13:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
14:         keyText.addKeyListener(this);
15:         BorderLayout bord = new BorderLayout();
16:         setLayout(bord);
17:         add(keyLabel, BorderLayout.NORTH);
18:         add(keyText, BorderLayout.CENTER);
19:         setVisible(true);
20:     }
21:
22:     public void keyTyped(KeyEvent input) {
23:         char key = input.getKeyChar();
24:         keyLabel.setText("You pressed " + key);
25:     }
26:
27:     public void keyPressed(KeyEvent txt) {
28:         // do nothing
29:     }
30:
31:     public void keyReleased(KeyEvent txt) {
32:         // do nothing
33:     }
34:
35:     private void setLookAndFeel() {
36:         try {
37:             UIManager.setLookAndFeel(
38:                 "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
39:             );
40:         } catch (Exception exc) {
41:             // ignore error
42:         }
43:     }
44:
45:     public static void main(String[] arguments) {
46:         KeyViewer frame = new KeyViewer();
47:     }
48: }


When you run the application, it should resemble Figure 15.1.

Figure 15.1. Handling keyboard events in a program.

Image

Enabling and Disabling Components

You might have seen a component in a program that appears shaded instead of its normal appearance.

Shading indicates that users cannot do anything to the component because it is disabled. Disabling and enabling components is accomplished with the setEnabled() method of the component. A Boolean value is sent as an argument to the method, so setEnabled(true) enables a component for use, and setEnabled(false) disables it.

The following statements create buttons with the labels Previous, Next, and Finish and disable the first button:

JButton previousButton = new JButton("Previous");
JButton nextButton = new JButton("Next");
JButton finishButton = new JButton("Finish");
previousButton.setEnabled(false);

This method is an effective way to prevent a component from sending a user event when it shouldn’t. For example, if you’re writing a Java application that collects a user’s address using text fields, you could disable a Save Address button until the user provided a street address, city, state and ZIP code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.77.63