Add KeyEvent to Canvas : Canvas « SWT « Java Tutorial






Add KeyEvent to Canvas
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class CanvasKeyEvent {

  public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    
    shell.setLayout(new RowLayout());
    final Canvas canvas = new Canvas(shell, SWT.NULL);
    canvas.setSize(500, 500);
    canvas.setBackground(display.getSystemColor(SWT.COLOR_YELLOW));

    canvas.addKeyListener(new KeyListener() {
      public void keyPressed(KeyEvent e) {
        GC gc = new GC(canvas);
        Rectangle rect = canvas.getClientArea();
        gc.fillRectangle(rect.x, rect.y, rect.width, rect.height);
        
        Font font = new Font(display, "Arial", 32, SWT.BOLD );
        gc.setFont(font);
        
        gc.drawString("" + e.character, 15, 10);
        
        gc.dispose();
        font.dispose();
      }

      public void keyReleased(KeyEvent e) {
      }
    });
    
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
  }

}








17.20.Canvas
17.20.1.Repaint CanvasRepaint Canvas
17.20.2.Canvas: scroll an image (flicker free, no double buffering)Canvas: scroll an image (flicker free, no double buffering)
17.20.3.Add Traverse event to CanvasAdd Traverse event to Canvas
17.20.4.Add Controls to CanvasAdd Controls to Canvas
17.20.5.Add KeyEvent to CanvasAdd KeyEvent to Canvas