Java Reference
In-Depth Information
Handling JComponent Events
There are many different types of events that all JComponent subclasses share. Most of these
come from parent classes, like Component and Container . First, you'll explore the use of
PropertyChangeListener , which is inherited from Container . Then you'll look at the use of two
event-handling capabilities shared by all JComponent subclasses: VetoableChangeListener and
AncestorListener . Finally, you'll see the complete set of listeners inherited from Component .
Listening to Component Events with a PropertyChangeListener
The JComponent class has several component bound properties, directly and indirectly. By
binding a PropertyChangeListener to the component, you can listen for particular JComponent
property changes, and then respond accordingly.
public interface PropertyChangeListener extends EventListener {
public void propertyChange(PropertyChangeEvent propertyChangeEvent);
}
To demonstrate, the PropertyChangeListener in Listing 4-1 demonstrates the behavior you
might need when listening for changes to an Action type property within a JButton component.
The property that changes determines which if block is executed.
Listing 4-1. Watching for Changes to a JButton
import java.beans.*;
import javax.swing.*;
public class ActionChangedListener implements PropertyChangeListener {
private JButton button;
public ActionChangedListener(JButton button) {
this.button = button;
}
public void propertyChange(PropertyChangeEvent e) {
String propertyName = e.getPropertyName();
if (e.getPropertyName().equals(Action.NAME)) {
String text = (String)e.getNewValue();
button.setText(text);
button.repaint();
} else if (propertyName.equals("enabled")) {
Boolean enabledState = (Boolean)e.getNewValue();
button.setEnabled(enabledState.booleanValue());
button.repaint();
Search WWH ::




Custom Search