Reputation: 775
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
Reputation: 9541
if( ((JFrame)getTopLevelAncestor()).getFocusOwner() == textField ) {
....
}
Upvotes: 0
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
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