Java Swing - Focus Listener

337 Views Asked by At

I have a custom Focus Listener for my java program and whenever I start the program its automatically focused in my first JTextField when it shouldn't be focused at all. I also cant un-focus off the JTextField without focusing on the other bottom JTextField and visa versa. It was working fine until I started using my custom Focus Listener.

program

Heres my Focus Listener:

public class FocusListener implements java.awt.event.FocusListener
{
    private final JTextField textField;
    private final String text;

    public FocusListener(JTextField textField, String text)
    {
        this.textField = textField;
        this.text = text;
    }

    @Override
    public void focusGained(FocusEvent e) {
        if (textField.getText().equals(text))
        {
            textField.setText("");
            textField.setForeground(Color.BLACK);
        }
    }
    @Override
    public void focusLost(FocusEvent e) {
        if (textField.getText().isEmpty())
        {
            textField.setForeground(Color.GRAY);
            textField.setText(text);
        }
    }
}
0

There are 0 best solutions below