Tuesday 6 December 2016

SWT: Key listener

KeyListener is used to capture key pressed and key released events. You can add keyListener to a widget using addkeyListener mehtod. You can remove the key listener using removeKeyListener method.

KeyListener interface provides following methods.

Method
Description
public void keyPressed(KeyEvent e)
Sent when a key is pressed on the system keyboard.
public void keyReleased(KeyEvent e)
Sent when a key is released on the system keyboard.

Ex:
Text text = new Text(shell, SWT.MULTI | SWT.BORDER);
text.setBounds(10, 10, 300, 100);

text.addKeyListener(new KeyListener() {

 @Override
 public void keyPressed(KeyEvent e) {
  
 }

 @Override
 public void keyReleased(KeyEvent e) {
  
 }

});

Following is the complete working application.
package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class Test {

 private static int shellWidth = 400;
 private static int shellHeight = 400;

 private static void addWidgetsToShell(Display display, Shell shell) {

  Text text = new Text(shell, SWT.MULTI | SWT.BORDER);
  text.setBounds(10, 10, 300, 100);

  text.addKeyListener(new KeyListener() {

   @Override
   public void keyPressed(KeyEvent e) {
    String result = "";
    switch (e.character) {
    case 0:
     result += " '\\0'";
     break;
    case SWT.BS:
     result += " '\\b'";
     break;
    case SWT.CR:
     result += " '\\r'";
     break;
    case SWT.DEL:
     result += " DEL";
     break;
    case SWT.ESC:
     result += " ESC";
     break;
    case SWT.LF:
     result += " '\\n'";
     break;
    default:
     result += " '" + e.character + "'";
     break;
    }
    System.out.println(result);
   }

   @Override
   public void keyReleased(KeyEvent e) {
    if (e.stateMask == SWT.CTRL && e.keyCode != SWT.CTRL)
     System.out.println("Command can execute here");
   }

  });
 }

 public static void main(String[] args) {

  /* Instantiate Display object, it represents SWT session */
  Display display = new Display();

  /*
   * Define Shell, it represent a window, You can add more than one shell
   * to Display
   */
  Shell shell = new Shell(display);
  shell.setSize(shellWidth, shellHeight);

  addWidgetsToShell(display, shell);

  /* Open shell window */
  shell.open();

  /*
   * Run the event dispatching loop until an exit condition occurs, which
   * is typically when the main shell window is closed by the user.
   */

  while (!shell.isDisposed()) {
   if (!display.readAndDispatch())
    display.sleep();
  }

  /* Dispose the display */
  display.dispose();
 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment