2013-10-07 79 views
1

我想爲複合添加一個關鍵偵聽器。 我的代碼如下:合成的關鍵監聽器?

@Override 
protected Control createDialogArea(Composite parent) { 
    //add swt text box , combo etc to parent 
} 

複合材料是:org.eclipse.swt.widgets.Composite
現在我想關鍵監聽器添加到複合父。
就像以前用戶按下ctrl或escape一樣,用戶應該會收到通知。
即使即使焦點在文本或組合字段上,也應該通知父監聽器。 感謝您的幫助。

回答

2

好吧,在這裏你去:添加Filter到您的Display。在Listener內,檢查當前焦點控制的父項是否爲CompositeShell。如果是這樣,你檢查關鍵代碼。

總之,如果您的焦點位於您的Composite「內」,並且在Composite「外部」時忽略它,則您將處理關鍵事件。

public static void main(String[] args) 
{ 
    Display display = new Display(); 
    final Shell shell = new Shell(display); 
    shell.setLayout(new GridLayout(1, false)); 

    final Composite content = new Composite(shell, SWT.NONE); 
    content.setLayout(new GridLayout(2, false)); 

    Text text = new Text(content, SWT.BORDER); 
    Button button = new Button(content, SWT.PUSH); 
    button.setText("Button"); 

    display.addFilter(SWT.KeyUp, new Listener() 
    { 
     @Override 
     public void handleEvent(Event e) 
     { 
      if (e.widget instanceof Control && isChild(content, (Control) e.widget)) 
      { 
       if ((e.stateMask & SWT.CTRL) == SWT.CTRL) 
       { 
        System.out.println("Ctrl pressed"); 
       } 
       else if(e.keyCode == SWT.ESC) 
       { 
        System.out.println("Esc pressed"); 
       } 
      } 
     } 
    }); 

    Text outsideText = new Text(shell, SWT.BORDER); 

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

private static boolean isChild(Control parent, Control child) 
{ 
    if (child.equals(parent)) 
     return true; 

    Composite p = child.getParent(); 

    if (p != null) 
     return isChild(parent, p); 
    else 
     return false; 
} 
+0

非常感謝!完美的作品! – Destructor