3

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 ?

2 Answers 2

5

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()...

3
  • There are huge number of controls which born and die in multiple threads. Is it possible to do such tracing for any control without explicit call addFocusListener ? Jun 25, 2013 at 3:52
  • Someone recommended me using AOP (i.e. aspectj) to add listeners to all controls or loading swt sources in eclipse workspace and hacks setFocus in it. I succesfully used last approach Jun 25, 2013 at 18:49
  • @PavelNuzhdin I'm glad you found a solution that's feasible for you!
    – Baz
    Jun 25, 2013 at 19:01
3

Add a focus listener that send a log message?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.