3

Having a Label and a Text control in SWT, how can I define a mnemonic on the label that will activate the input field? I found a couple of examples on how to set a mnemonic on a Button, but how do I define a mnemonic on a Label and make it point to a different input control?

user1438038
  • 5,821
  • 6
  • 60
  • 94

1 Answers1

4

In the simplest case, you can define a mnemonic just as with a button.

Label label = new Label( parent, SWT.NONE );
label.setText( "&Name" );
Text text = new Text( parent, SWT.BORDER );

When pressing Alt+N, the control that is next in the tab order to the label will be focused, in this case, the text input field .

If another control should get the focus, you'll need to add a traverse listener to the label and manually give focus to the desired control. For example

Label label = new Label( parent, SWT.NONE );
label.setText( "&Name" );
label.addListener( SWT.Traverse, new Listener() {
  @Override
  public void handleEvent( Event event ) {
    if( event.detail == SWT.TRAVERSE_MNEMONIC ) {
      event.doit = false;
      otherControl.setFocus();
    }
  }
} );
Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79