Java Reference
In-Depth Information
Note Part of the problem of creating responsive user interfaces is figuring out which event listener to
associate with a component to get the appropriate response for the event you're interested in. For the most
part, this process becomes more natural with practice. Until then, you can examine the different component
APIs for a pair of add/remove listener methods, or reference the appropriate component material in this topic.
Creating an Instance of the Listener
Next, you simply create an instance of the listener you just defined.
ActionListener actionListener = new AnActionListener();
If you use anonymous inner classes for event listeners, you can combine steps 1 and 2:
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("I was selected.");
}
};
Registering the Listener with a Component
Once you've created the listener, you can associate it with the appropriate component. Assuming
the JButton has already been created with a reference stored in the variable button , this would
merely entail calling the button's addActionListener() method:
button.addActionListener(actionListener);
If the class that you're currently defining is the class that implements the event listener
interface, you don't need to create a separate instance of the listener. You just need to associate
your class as the listener for the component. The following source demonstrates this:
public class YourClass implements ActionListener {
... // Other code for your class
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("I was selected.");
}
// Code within some method
JButton button = new JButton(...);
button.addActionListener(this);
// More code within some method
}
Using event handlers such as creating a listener and associating it to a component is the
basic way to respond to events with the Swing components. The specifics of which listener
works with which component are covered in later chapters, when each component is described.
In the following sections, you'll learn about some additional ways to respond to events.
 
Search WWH ::




Custom Search