Java Reference
In-Depth Information
9. An event is an object representing a user's interaction with a graphical component.
A listener is an object that handles an event. The ActionListener interface is
used to handle action events.
10. To handle an event, you must write a class that implements the ActionListener
interface. It must contain a method named actionPerformed . You must call the
addActionListener method on the component in question in order to attach
your new listener to it.
11. import java.awt.event.*;
import javax.swing.*;
public class GreetingListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(null,
"Greetings, Earthling!");
}
}
12. Object-oriented GUIs store their components as fields. This is useful because such
a GUI can also be made into an action listener that has access to these components.
13. The MouseInputListener interface and MouseInputAdapter class are used
when you are implementing mouse listeners. This usage differs from using
ActionListener because you extend a class rather than implementing an inter-
face, due to the large number of methods in the interface. You're also more likely
to interact with a mouse listener's MouseEvent parameter than with the
ActionEvent parameter of an action listener.
14. // responds to mouse movement events
public void mouseMoved(MouseEvent event) {
if (event.getY() < label.getHeight() / 2) {
label.setForeground(Color.BLUE);
} else {
label.setForeground(Color.RED);
}
label.setText("(" + event.getX() + ", " +
event.getY() + ")");
}
15. When you are drawing 2D graphics, you should extend the JPanel class and write
a paintComponent method.
16. import java.awt.*;
import javax.swing.*;
public class RedCirclePanel extends JPanel {
Search WWH ::




Custom Search