Ricco
Ricco

Reputation: 775

Checking if a JTextfield is selected or not

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

Upvotes: 4

Views: 22318

Answers (4)

Mark Jeronimus
Mark Jeronimus

Reputation: 9541

if( ((JFrame)getTopLevelAncestor()).getFocusOwner() == textField ) {
    ....
}

Upvotes: 0

COD3BOY
COD3BOY

Reputation: 12112

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.

Upvotes: 2

Deco
Deco

Reputation: 3321

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

    }
}

Upvotes: 7

hage
hage

Reputation: 6163

You may try isFocusOwner()

Upvotes: 6

Related Questions