Pavel Nuzhdin
Pavel Nuzhdin

Reputation: 854

How to find why control loses focus

I have bunch of controls, views and editors. I found that editor is loosing focus sometimes. This issue hard to reproduce in debug because when I switch to breakpoint in debugger and back to application, editor is never loses focus.

Can you recommend tips & tricks how to find why control loses focus ?

Upvotes: 3

Views: 820

Answers (2)

Baz
Baz

Reputation: 36904

Adding some context to @david's answer:

You can add a FocusListener to all your Widgets. Within this listener you can output some information about the widget that lost/gained the focus.

To make things easier, you can add meta-data to the Widgets using Widget#setData(Object).


Here is a code example that should help you figure things out:

public static void main(String[] args)
{
    Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("StackOverflow");
    shell.setLayout(new FillLayout());

    FocusListener focusListener = new FocusListener()
    {
        @Override
        public void focusLost(FocusEvent e)
        {
            System.out.println("Focus out: " + e.widget.getData());
        }

        @Override
        public void focusGained(FocusEvent e)
        {
            System.out.println("Focus in: " + e.widget.getData());
        }
    };

    Text text = new Text(shell, SWT.BORDER);
    text.setText("Text");
    text.setData("Text");
    text.addFocusListener(focusListener);

    Button button = new Button(shell, SWT.PUSH);
    button.setText("Button");
    button.setData("Button");
    button.addFocusListener(focusListener);

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

Notice the utilization of setData() and getData()...

Upvotes: 5

David G
David G

Reputation: 4014

Add a focus listener that send a log message?

Upvotes: 3

Related Questions