Natasha
Natasha

Reputation: 1480

jTextFields requesting focus (if empty after lostFocus) not working

I have 2 jTextFields and both have listeners for a lostFocus event, if the first textfield lost focus and is empty I want it to regain focus,and almost the same for the second field. I tried this:

String str = MyTextField.getText();
if (str.isEmpty()) 
    MyTextField.requestFocusInWindow();
else ...

and it worked at first , but now even if the first textfield is empty the second gains focus and after this everything hangs, I think maybe there are some concurrency issues... Please explain the reason and help me with a solution

Upvotes: 0

Views: 1023

Answers (1)

Extreme Coders
Extreme Coders

Reputation: 3511

Use InputVerifier

From the javadocs,

A component's input verifier is consulted whenever the component is about to lose the focus. If the component's value is not acceptable, the input verifier can take appropriate action, such as refusing to yield the focus on the component or replacing the user's input with the last valid value and then allowing the focus to transfer to the next component. However, InputVerifier is not called when the focus is transferred to another toplevel component.

Here is a sample code based on yours that prevents tabbing to the other text field if the textfield is empty

import javax.swing.*;
import java.awt.*;

public class FoucsDemo
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new FoucsDemo();
            }
        });

    }

    FoucsDemo()
    {
        JFrame jFrame=new JFrame("Input Verifier");
        jFrame.setLayout(new GridLayout(2,1,1,5));
        JTextField jTextField1=new JTextField(10);
        JTextField jTextField2=new JTextField(10);
        jTextField1.setInputVerifier(new Verify());
        jTextField2.setInputVerifier(new Verify());
        jFrame.add(jTextField1);
        jFrame.add(jTextField2);
        jFrame.pack();
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jFrame.setVisible(true);
    }

    class Verify extends InputVerifier
    {
        @Override
        public boolean verify(JComponent input)
        {
            return !((JTextField) input).getText().equals("");
        }
    }
}

Upvotes: 1

Related Questions