4

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");
        }
    });
    }
}
Ricco
  • 775
  • 5
  • 11
  • 19

4 Answers4

7

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
            }
        });

    }
}
Deco
  • 3,261
  • 17
  • 25
6

You may try isFocusOwner()

hage
  • 5,966
  • 3
  • 32
  • 42
2

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.

COD3BOY
  • 11,964
  • 1
  • 38
  • 56
0
if( ((JFrame)getTopLevelAncestor()).getFocusOwner() == textField ) {
    ....
}
Mark Jeronimus
  • 9,278
  • 3
  • 37
  • 50