Listeners in java example

Introduction to Event Listeners

If you have read any of the component how-to pages, you probably already know the basics of event listeners.

Let us look at one of the simplest event handling examples possible. It is called Beeper, and it features a button that beeps when you click it.

Click the Launch button to run Beeper using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.

A Click Me Beeper Button

You can find the entire program in Beeper.java . Here is the code that implements the event handling for the button:

public class Beeper . implements ActionListener < . //where initialization occurs: button.addActionListener(this); . public void actionPerformed(ActionEvent e) < . //Make a beep sound. > >

The Beeper class implements the ActionListener interface, which contains one method: actionPerformed . Since Beeper implements ActionListener , a Beeper object can register as a listener for the action events that buttons fire. Once the Beeper has been registered using the Button addActionListener method, the Beeper ‘s actionPerformed method is called every time the button is clicked.

A More Complex Example

The event model, which you saw at its simplest in the preceding example, is quite powerful and flexible. Any number of event listener objects can listen for all kinds of events from any number of event source objects. For example, a program might create one listener per event source. Or a program might have a single listener for all events from all sources. A program can even have more than one listener for a single kind of event from a single event source.

Читайте также:  Вывести код символа char java

Multiple listeners can register to be notified of events of a particular type from a particular source. Also, the same listener can listen to notifications from different objects.

Each event is represented by an object that gives information about the event and identifies the event source. Event sources are often components or models, but other kinds of objects can also be event sources.

Whenever you want to detect events from a particular component, first check the how-to section for that component. A list of the component how-to sections is here. The how-to sections give examples of handling the events that you are most likely to care about. In How to Use Color Choosers, for instance, you will find an example of writing a change listener to track when the color changes in the color chooser.

The following example demonstrates that event listeners can be registered on multiple objects and that the same event can be sent to multiple listeners. The example contains two event sources ( JButton instances) and two event listeners. One of the event listeners (an instance of a class called MultiListener ) listens for events from both buttons. When it receives an event, it adds the event’s «action command» (which is set to the text on the button’s label) to the top text area. The second event listener (an instance of a class called Eavesdropper ) listens for events on only one of the buttons. When it receives an event, it adds the action command to the bottom text area.

Try this:

  1. Click the Launch button to run MultiListener using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.
  2. Click the Blah blah blah button. Only the MultiListener object is registered to listen to this button.
  3. Click the You do not say! button. Both the MultiListener object and the Eavesdropper object are registered to listen to this button.

You can find the entire program in MultiListener.java . Here is the code that implements the event handling for the button:

public class MultiListener . implements ActionListener < . //where initialization occurs: button1.addActionListener(this); button2.addActionListener(this); button2.addActionListener(new Eavesdropper(bottomTextArea)); > public void actionPerformed(ActionEvent e) < topTextArea.append(e.getActionCommand() + newline); >> class Eavesdropper implements ActionListener < . public void actionPerformed(ActionEvent e) < myTextArea.append(e.getActionCommand() + newline); >>

In the above code, both MultiListener and Eavesdropper implement the ActionListener interface and register as action listeners using the JButton addActionListener method. Both classes’ implementations of the actionPerformed method are similar: they simply add the event’s action command to a text area.

Источник

How to Write an Item Listener

Item events are fired by components that implement the ItemSelectable interface. Generally, ItemSelectable components maintain on/off state for one or more items. The Swing components that fire item events include buttons like check boxes, check menu items, toggle buttons etc. and combo boxes.

Here is some item-event handling code taken from ComponentEventDemo.java :

//where initialization occurs checkbox.addItemListener(this); . public void itemStateChanged(ItemEvent e) < if (e.getStateChange() == ItemEvent.SELECTED) < label.setVisible(true); . >else < label.setVisible(false); >>

The Item Listener API

Because ItemListener has only one method, it has no corresponding adapter class.

Method Purpose
itemStateChanged(ItemEvent) Called just after a state change in the listened-to component.
Method Purpose
Object getItem() Returns the component-specific object associated with the item whose state changed. Often this is a String containing the text on the selected item.
ItemSelectable getItemSelectable() Returns the component that fired the item event. You can use this instead of the getSource method.
int getStateChange() Returns the new state of the item. The ItemEvent class defines two states: SELECTED and DESELECTED .

Examples that Use Item Listeners

The following table lists some examples that use item listeners.

Example Where Described Notes
ComponentEventDemo This section and How to Write a Component Listener Listens for item events on a check box, which determines whether a label is visible.
CheckBoxDemo How to Use Check Boxes Four check boxes share one item listener, which uses getItemSelected to determine which check box fired the event.
MenuDemo How to Use Menus Listens for item events on a check box menu item.
MenuDemo How to Use Scroll Panes Listens for item events on a toggle button.

Источник

Lesson: Writing Event Listeners

This lesson gives you details about writing event listeners. You might not need to read this section. Your first source of information for event should be the how-to section for the component in question. Each component’s section shows code for handling the events most commonly needed when implementing the component. For example, How to Use Check Boxes shows you how to handle mouse clicks on check boxes using an item listener.

Some Simple Event-Handling Examples

The programs in this section illustrate events and event handling.

General Information about Writing Event Listeners

This section provides information that is useful for handling all types of events. One of the topics includes information on using adapters and inner classes to implement event handlers.

Listeners Supported by Swing Components

This is the place to find out which Swing components can fire which kinds of events. You might want to bookmark this section so you can easily find its quick-reference table.

Implementing Listeners for Commonly Handled Events

This section has detailed information and examples of writing each common kind of event listener.

Listener API Table

This section features a quick-reference table that shows each listener, its adapter class (if any), and its methods.

Solving Common Event-Handling Problems

If you are having some hard-to-debug problems related to handling events, you might find the solution here.

Questions and Exercises

Try these questions and exercises to test what you have learned in this lesson.

If you are interested in using JavaFX to create your GUI, see Handling JavaFX Events.

Источник

Оцените статью