Java Reference
In-Depth Information
EXAMPLE 12-9
This example shows how to handle the following mouse events: mouse clicked, mouse
entered, mouse exited, mouse pressed, and mouse released. To handle these events, we
use the methods of the interface MouseListener . The MouseExample program
contains six labels corresponding to the five mouse events and one label to display the
mouse location. When you run this program and use the mouse, the foreground color of
the label corresponding to the generated mouse event changes, and the mouse location
where the event occurred is displayed.
//Program to illustrate mouse events
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MouseExample extends JFrame
implements MouseListener
{
private static int WIDTH = 350;
private static int HEIGHT = 250;
//GUI components
private JLabel[] labelJL;
public MouseExample()
{
setTitle("Mouse Events");
Container pane = getContentPane();
setSize(WIDTH,HEIGHT);
GridLayout gridMgr = new GridLayout(6, 1, 10, 10);
pane.setLayout(gridMgr);
labelJL = new JLabel[6];
labelJL[0] = new JLabel("Mouse Clicked",
SwingConstants.CENTER);
labelJL[1] = new JLabel("Mouse Entered",
SwingConstants.CENTER);
labelJL[2] = new JLabel("Mouse Exited",
SwingConstants.CENTER);
labelJL[3] = new JLabel("Mouse Pressed",
SwingConstants.CENTER);
labelJL[4] = new JLabel("Mouse Released",
SwingConstants.CENTER);
labelJL[5] = new JLabel("",SwingConstants.CENTER);
1
2
Search WWH ::




Custom Search