Frage

I want to add a key listener for a composite. My code is as follows:

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

The composite is a: org.eclipse.swt.widgets.Composite
Now i want to add a key listener to the composite parent.
Like when ever user presses ctrl or escape, user should get notified.
Even if the focus is on one the text or combo field even then , the parent listener should be notified. Thanks for the help.

War es hilfreich?

Lösung

Ok, here you go: Add a Filter to your Display. Within the Listener you check if the parent of the current focus control is the Shell of your Composite. If so, you check the key code.

In conclusion, you will handle the key event, if your focus is "within" your Composite and ignore it if it is "outside" your 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;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top