【问题标题】:Key listener for composite?复合材料的关键监听器?
【发布时间】:2013-10-13 15:58:30
【问题描述】:

我想为组合添加一个键监听器。 我的代码如下:

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

复合是:org.eclipse.swt.widgets.Composite
现在我想向复合父级添加一个关键侦听器。
就像用户按下 ctrl 或退出时一样,用户应该得到通知。
即使焦点在文本或组合字段之一上,也应通知父侦听器。 感谢您的帮助。

【问题讨论】:

    标签: java swt listener keylistener composite


    【解决方案1】:

    好的,开始吧:将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;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-06
      • 2012-04-29
      • 2012-08-08
      • 1970-01-01
      • 2012-06-17
      • 1970-01-01
      • 2013-12-23
      • 1970-01-01
      相关资源
      最近更新 更多