views:

8

answers:

1

Hi,

I have a problem with the focus traversal system in Java. When I tab between components in a pane in my application everything works fine Tab moves the focus to the next component.

Some of my components perform validation on loss of focus, if the validation returns errors then the screens save button is disabled.

My problem occurs when the validated component is followed by the save button.

Tab removes focus from the validated component and begins the asynchronous process of assigning focus to the next component that is enabled (The Save Button)

Next my validation kicks in and disables the save button

The asynchronous process then finished and attempts to assign focus to the now disabled Save button.

The Focus now becomes trapped and tabbing no longer shifts focus because no component actually has the focus.

Has anyone else come across this problem, how did you solve the problem of having the validation and disablement carried out before the focus traversal event started?

A: 

You could use an InputVerifier to validate the text field. In this case focus will be placed back on the text field in error.

Or you could change your focus listener to handle this situation. Something like:

FocusListener fl = new FocusAdapter()
{
    public void focusLost(final FocusEvent e)
    {
        JTextField tf = (JTextField)e.getSource();

        if (tf.getDocument().getLength() < 1)
        {
            System.out.println("Error");
            button.setEnabled( false );

            Component c =  e.getOppositeComponent();

            if (c instanceof JButton
            &&  c.isEnabled() == false)
            {
                tf.requestFocusInWindow();
            }
        }
        else
            button.setEnabled( true );
    }
};
camickr