|
In Chapter 15, you learned how to create a variety of component types:
Buttons
Check boxes
Choices
Labels
Menus and menu items
Scrollbars
Text areas
Text fields
Now you will learn how to respond to user input activity on each type of component. You already know how to respond to buttons. Labels do not send events. In the rest of this chapter, you will learn how to detect events from the other component types.
In this section, you'll learn how to respond to activity from check boxes and choices. As a reminder, Figure 16.16 shows a check box and a choice.
Figure 16.16: Check box and choice
Check boxes and choices don't have action listeners, but they have something similar: item listeners. An object that wants to be notified when activity happens in a check box or a choice must implement the java.awt.event.ItemListener interface. This interface defines one method:
public void itemStateChanged(ItemEvent e);
When a check box or choice is activated, an itemStateChanged() call is made to each of its item listeners. You can call addItemListener(ItemListener x) to add an item listener to a check box's or choice's list. You can call removeItemListener(ItemListener x) to remove an item listener from a check box's or choice's list.
Within an itemStateChanged() method, you can determine which component was activated by calling the ItemEvent's getSource() method, just as you would call getSource() on an ActionEvent in an actionPerformed() method. (In fact, ActionEvent, ItemEvent, and the other event classes you will learn about in this chapter all inherit getSource() from a superclass that they all extend.)
The following code builds a GUI that contains a check box, a choice, and a text field. When the check box or the choice are activated, the text field displays an appropriate message.
import java.awt.*; import java.awt.event.*; public class CboxAndChoice extends Frame implements ItemListener { private Checkbox cbox; private Choice ch; private TextField tf; CboxAndChoice() { setLayout(new FlowLayout()); cbox = new Checkbox("Click here"); cbox.addItemListener(this); add(cbox); ch = new Choice(); ch.add("Red"); ch.add("Yellow"); ch.add("Blue"); ch.add("Plaid"); ch.add("Paisley"); ch.addItemListener(this); add(ch); tf = new TextField(25); add(tf); setSize(475, 75); } public void itemStateChanged(ItemEvent e) { if (e.getSource() == cbox) tf.setText("Checkbox: " + cbox.getState()); else tf.setText("Choice: " + ch.getSelectedIndex()); } public static void main(String[] args) { (new CboxAndChoice()).setVisible(true); } }
The itemStateChanged() method calls the event's getSource() method to determine which component was activated. The getState() method of Checkbox returns true if the component is checked, and false if it is not checked. The getSelectedIndex() method of Choice returns the position (counting from 0) of the component's selected item.
Figure 16.17 shows the GUI.
Figure 16.17: Receiving events from a check box and a choice
By now, you probably get the feel of it. Components have lists of listeners. When the components are activated, method calls are made to the listeners.
That's about it. You'll probably have an easy time with the next several sections.
Text fields and text areas both send text events to text listeners. The events are sent each time a user types a keystroke. The TextListener interface defines one method:
public void textValueChanged(TextEvent e);
To add an object to a text field's or text area's list of text listeners, call the component's addTextListener() method, passing in the listener object.
Text fields (but not text areas) can also send action events to action listeners. This happens when the user presses the Enter key.
We won't work through a detailed code example, because if you understand how to handle action and item events, handling text events should be obvious. Instead, let's step back for a moment and look at the big picture.
A Java GUI consists of a number of components of various types. Each component may have zero, one, or multiple listeners for each event type that the component supports. When a component is activated, the Event dispatch thread calls the appropriate method of each listener.
The Event Lab animated illustration lets you experiment with multiple component, listener, and event types, without writing any code. Event Lab is an extension of Simple Event Lab. In addition to buttons, you can create check boxes, choices, and text fields. When you create a listener class, you select which listener interfaces it will implement. (Your choices are ActionListener, ItemListener, and TextListener. Remember that classes are allowed to implement more than one interface, so listener classes are allowed to implement more than one listener interface.)
Start the program by typing java events.EventLab. You control the program just as you did Simple Event Lab. Figure 16.18 shows Event Lab with a fairly complicated configuration.
Figure 16.18: Event Lab
Configure Event Lab with your own complicated setup. Then click the Run button. The simulated components will become real. Activate your buttons, check boxes, choices, and text fields until you have a good feel for how various component types send various event types to various listeners in an event-driven GUI program.
In Chapter 15, you saw the simplest way to populate menus. It looked something like this:
Menu fileMenu = new Menu("File"); fileMenu.add("Open…"); fileMenu.add("Close"); ...
The add() calls created individual menu items. That approach was good for showing you what Java menus look like, but there is a better way if you want to receive event notification from the menu items. The preceding code can be rewritten as follows:
Menu fileMenu = new Menu("File"); MenuItem openMI = new MenuItem("Open…"); fileMenu.add(openMI); MenuItem closeMI = new MenuItem("Close"); fileMenu.add(closeMI); ...
Like buttons, menu items send action events to action listeners. So to add menuListener to openMI's list of action listeners, you would call
openMI.addActionListener(menuListener);
There's no need to present a detailed example, because the code is so similar to the code you've already seen that handles action events from buttons.
Scrollbars send adjustment events to adjustment listeners. Adjustment listeners implement the java.awt.event.AdjustmentListener interface. Once again, we have a listener interface that defines a single method:
public void adjustmentValueChanged(AdjustmentEvent e);
An object gets added to a scrollbar's listener list via a call to the addAdjustmentListener() method. The following code receives adjustment notification from a scrollbar, and reports the scrollbar's value to a text field. The code uses the getvalue() method of the Scrollbar class. The return type is int:
import java.awt.*; import java.awt.event.*; public class BarAndTF extends Frame implements AdjustmentListener { private Scrollbar bar; private TextField tf; BarAndTF() { bar = new Scrollbar(Scrollbar.HORIZONTAL); bar.addAdjustmentListener(this); add(bar, "North"); Panel pan = new Panel(); tf = new TextField(" "); pan.add(tf); add(pan, "South"); setSize(300, 100); } public void adjustmentValueChanged(AdjustmentEvent e) { tf.setText("Value = " + bar.getValue()); } public static void main(String[] args) { (new BarAndTF()).setVisible(true); } }
The GUI is shown in Figure 16.19.
Figure 16.19: Scrollbar and text field
Now you know how to respond to events from all the component types you learned about in Chapter 15. In the next chapter, which finishes this book, you will work through a detailed final project that draws from everything you have learned so far, from Chapter 1 through the period at the end of this sentence.
|