Checking if a JTextfield is selected or not

20,710

Solution 1

You will need to use the focusGained and focusLost events to see when it has been selected, and when it is deselected (i.e. gained/lost focus).

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JTextField;

public class Main {

    public static void main(String args[]) {
        final JTextField textField = new JTextField();
        textField.addFocusListener(new FocusListener() {

            @Override
            public void focusGained(FocusEvent e) {
                //Your code here
            }

            @Override
            public void focusLost(FocusEvent e) {
                //Your code here
            }
        });

    }
}

Solution 2

You may try isFocusOwner()

Solution 3

Is it possible to check if a jtextfield has been selected / de-selected

Yes, use focusGained and focusLost events.

the text field has been clicked and the cursor is now inside the field ?

Use isFocusOwner() which returns true if this Component is the focus owner.

Share:
20,710
Ricco
Author by

Ricco

Updated on August 07, 2020

Comments

  • Ricco
    Ricco almost 4 years

    Is it possible to check if a jtextfield has been selected / de-selected (ie the text field has been clicked and the cursor is now inside the field)?

    //EDIT thanks to the help below here is a working example

    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    
    @SuppressWarnings("serial")
    public class test extends JFrame {
    
    private static JPanel panel = new JPanel();
    private static JTextField textField = new JTextField(20);
    private static JTextField textField2 = new JTextField(20);
    
    public test() {
        panel.add(textField);
        panel.add(textField2);
        this.add(panel);
    }
    
    public static void main(String args[]) {
    
        test frame = new test();
        frame.setVisible(true);
        frame.setSize(500, 300);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        textField.addFocusListener(new FocusListener() {
    
            @Override
            public void focusGained(FocusEvent e) {
                System.out.println("selected");
            }
    
            @Override
            public void focusLost(FocusEvent e) {
                System.out.println("de-selected");
            }
        });
        }
    }