Typed and untyped events

For processing an event, it is necessary to use a listener. In the first versions of the SWT API, there were only untyped listeners. These listeners provide a simple mechanism to handle the events. There is only one generic interface called Listener and an event class called Event. In order to add a listener, it is necessary to use the addListener method.

After some discussion among the Eclipse community, it was decided that a more familiar pattern would be introduced in the SWT API. These are the typed listeners, that were defined in terms of the untyped ones, and they can be found in the org.eclipse.swt.events package. We can see the difference among them in the following snippet of code:

...
widget.addListener(SWT.Dispose, new Listener() { 
    public void handleEvent(Event event) { 
        // widget was disposed 
    } 
}); 
...
...
widget.addDisposeListener(new DisposeListener() { 
    public void widgetDisposed(DisposeEvent event) { 
        // widget was disposed 
    } 
});
...

In this example, DisposeListener is an interface. When there is more than one method defined in the listener, the SWT API provides an adapter class with these methods. For instance, the SelectionListener interface has two methods, widgetSelected and widgetDefaultSelected, that takes SelectionEvents as arguments. As a result, the SelectionAdapter class contains both methods.

A table containing the typed events and the corresponding untyped ones is shown as follows:

Event

Listener

Method

Untyped event

ArmEvent

ArmListener

widgetArmed

SWT.Arm

ControlEvent

ControlListener

ControlAdapter

controlMoved

controlResized

SWT.Move

SWT.Resize

DisposeEvent

DisposeListener

widgetDisposed

SWT.Dispose

FocusEvent

FocusListener

FocusAdapter

focusGained

focusLost

SWT.FocusIn

SWT.FocusOut

HelpEvent

HelpListener

helpRequested

SWT.Help

KeyEvent

KeyListener

KeyAdapter

keyPressed

keyReleased

SWT.KeyPressed

SWT.KeyReleased

MenuEvent

MenuListener

MenuAdapter

menuHidden

menuShown

SWT.Hide

SWT.Show

ModifyEvent

ModifyListener

modifyText

SWT.Modify

MouseEvent

MouseListener

MouseAdapter

mouseDoubleClick

mouseDown

mouseUp

SWT.MouseDoubleClick

SWT.MouseDown

SWT.MouseUp

MouseMoveEvent

MouseMoveListener

MouseMove

SWT.MouseMove

MouseTrackEvent

MouseTrackListener

MouseTrackAdapter

mouseEnter

mouseExit

mouseHover

SWT.MouseEnter

SWT.MouseExit

SWT.MouseHover

PaintEvent

PaintListener

paintControl

SWT.Paint

SelectionEvent

SelectionListener

SelectionAdapter

widgetDefaultSelected

widgetSelected

SWT.DefaultSelection

SWT.Selection

ShellEvent

ShellListener

ShellAdapter

shellActivated

shellClosed

shellDeactivated

shellDeiconified

shellIconified

SWT.Activate

SWT.Close

SWT.Deactivate

SWT.Deiconify

SWT.Iconify

TraverseEvent

TraverseListener

keyTraversed

SWT.Traverse

TreeEvent

TreeListener

TreeAdapter

treeCollapsed

treeExpanded

SWT.Collapse

SWT.Expand

VerifyEvent

VerifyListener

verifyText

SWT.Verify

The adapters mentioned in the preceding table are only available for the events whose listeners have more than one method. Adapter objects can be created using a similar structure, the addXListener:

...
button.addMouseListener(new MouseAdapter() 
{ 
  public void mouseDoubleClick(MouseEvent e) 
  { 
      System.out.println("Double click."); 
  } 
)}; 
  ......

Since there are several events and listeners, it is difficult to focus on all of them for an explanation. In the following subsections, we try to give some examples of how to use the most common ones.

KeyEvent

Most of the events are straightforward for understanding and use. Nonetheless, the KeyEvent one, particularly, might need a better explanation. The KeyEvent class is created when a key is pressed by the user. It has two subclasses: TraverseEvent and VerifyEvent. A TraverseEvent is generated when the user presses the arrow key or the Tab key to reach a different widget, and the VerifyEvent subclass is activated when the user enters text into a widget.

Three member fields of the KeyEvent class typically used are as follows:

  • character: It provides a char value representing the pressed key
  • stateMask: It returns an integer that represents the state of the keyboard modification (it is possible to verify if some Alt, Ctrl, Shift, or command keys are being pressed)
  • keyCode: It provides the SWT public constants corresponding to the typed key

The following snippet of code shows an example of how to use the KeyEvent class:

public class ComboListenerEx {    
        public static void main(String[] args) { 
            Display display = new Display(); 
            Shell s = new Shell(display); 
            
            s.setSize(500,400); 
            s.setText("Combo KeyListener"); 
            s.setLayout(new RowLayout( )); 
            final Combo c = new Combo(s, SWT.DROP_DOWN | SWT.BORDER); 
            c.add("Brazil"); 
            c.add("Argentina"); 
            c.add("Spain"); 
                        
           c.addKeyListener(new KeyListener( ) { 
                String selectedItem = ""; 
                public void keyPressed(KeyEvent e) { 
                    if(c.getText( ).length( ) > 0) { 
                        return; 
                    } 
                    String key = Character.toString(e.character); 
                    String[] items = c.getItems( ); 
                    for(int i =0;i<items.length;i++) { 
                        if(items[i].toLowerCase( ).startsWith(key.toLowerCase( ))) { 
                                   c.select(i); 
                            selectedItem = items[i]; 
                            return; 
                        } 
                    } 
                } 
                public void keyReleased(KeyEvent e) { 
                    if(selectedItem.length( ) > 0) 
                    c.setText(selectedItem); 
                    selectedItem = ""; 
                } 
            });        
            s.open( ); 
            while(!s.isDisposed( )) { 
                if(!display.readAndDispatch( )) 
                    display.sleep( ); 
            } 
            display.dispose( ); 
        }
}

This example creates a simple combo widget. Since it is of the SWT.DROP_DOWN style, it is editable. The objective of this piece of code is to select the item corresponding to the first letter pressed by the user. For instance, if the letter pressed was the B key, the "Brazil" item would be selected.

MouseEvent

A MouseEvent occurs when a mouse button is pressed. A MouseListener can be used to handle three types of events:

  • MouseButtonPressed: This event takes place when a button is pressed, but not released
  • MouseButtonReleased: This event takes place when a button that has been pressed is released
  • MouseDoubleClick: This event takes place when a mouse button is double-clicked. Each of the these events have a corresponding method in the listener class that is called when an event takes place.

The following code snippet shows a listener handling mouse events:

…
public class MouseExample { 
    public static void main(String[] args) { 
        Display display = new Display(); 
        final Shell s = new Shell(display); 
        s.setSize(500,400); 
        s.setText("MouseEvent"); 
        s.open(); 

        s.addMouseListener(new MouseListener() { 
                public void mouseDown(MouseEvent e) { 
                       System.out.println("Position:" + e.x + " " + e.y);
                }
                 public void mouseUp(MouseEvent e) { 
                       System.out.println("Position2:" + e.x + " " + e.y); 
                }
                public void mouseDoubleClick(MouseEvent e) { 
                       System.out.println("Double click");
                }
        });
        while(!s.isDisposed( )){ 
                if(!display.readAndDispatch( )) 
                        display.sleep( ); 
        }
        display.dispose( );
    }
}
…

In this example, the mouseUp and mouseDown methods are triggered when a mouse click occurs. The mouseDoubleClick method shows a message in the console when a double-click happens.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset