Using MouseListener

MouseListener is used to respond to events that occur when a mouse button is pressed. MouseListener responds to three distinct mouse events:

MouseButtonPressed

When a mouse button is pressed, but not yet released

MouseButtonReleased

When a mouse button that has been pressed is released

MouseDoubleClick

When a mouse button is double-clicked

Each event has a corresponding method in the MouseListener class that is called at the occurrence of the event. The developer’s task when using MouseListener is to determine which event is appropriate for the desired action and to develop code in the corresponding method. An example to consider is an interface that displays the mouse location in a Label whenever a mouse button is pressed.

How do I do that?

Example 14-2 demonstrates a possible use of MouseListener.

Example 14-2. Using MouseListener

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.*;
public class MouseListenerExample {
    final Display d;
    final Shell s;
    public MouseListenerExample( )
    {
        d = new Display( );
        s = new Shell(d);
        
        s.setSize(250,200);
        s.setImage(new Image(d, "c:\\icons\\JavaCup.ico"));
        s.setText("A MouseListener Example");
        s.open( );
        
        s.addMouseListener(new MouseListener( ) {
            public void mouseDown(MouseEvent e) {
                Label l = new Label(s, SWT.FLAT);
                l.setText("Mouse Button Down at:" + e.x + " " + e.y);
                l.setBounds(e.x,e.y, 150,15);
                
            }
            public void mouseUp(MouseEvent e) {
                Label l ...

Get SWT: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.