Reputation: 2563
I have a FocusListener to select all the text in a JTextField when this JTextField gets the focus:
final FocusListener fl= new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
final JTextField tf= (JTextField) e.getComponent();
tf.selectAll();
}
@Override
public void focusLost(FocusEvent e) {
final JTextField tf= (JTextField) e.getComponent();
tf.select(-1, -1);
}
}
However, I want that this only happens if the user switches the focus with the tab key. It should not happen if the user clicks on the new component. But the FocusEvent doesn't provide such information. Is there a way to distinguish these cases?
Upvotes: 2
Views: 1576
Reputation: 1
You just need to check if the mouse is located over the textfield.
final FocusListener fl = new FocusListener ()
{
@Override
public void focusGained(FocusEvent e)
{
final JTextField tf= (JTextField) e.getComponent();
//check for mouse
if(tf.getMousePosition == null)
{
tf.selectAll();
}
}
@Override
public void focusLost(FocusEvent e) {}
}
Upvotes: -1
Reputation: 386
This do the job for one JTextField(you can tranform it for more)(it's not good way) but it works... I made a window(frame) and add two JTextFields (field 1,field 2) I use the Focuslistener you have had given(no exactly). I use a flag to keep it work. Let me know if your job is done with this....
import java.awt.FlowLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class cl implements MouseListener{
private boolean flag=false;
JFrame frame = new JFrame();
JTextField field = new JTextField(10);
JTextField field2 = new JTextField(10);
public cl(){ //Constructor
frame.setSize(100,350);
frame.setLocationRelativeTo(null);
frame.setLayout(new FlowLayout());
frame.add(field);
frame.add(field2);
frame.setVisible(true);
field.addMouseListener(this); //add MouseListene to JTextField field.
field.addFocusListener(new FocusListener(){
@Override
public void focusGained(FocusEvent e) {
if(flag==true){ //if flag=true;
final JTextField tf= (JTextField) e.getComponent();
tf.selectAll();
flag=false;
}
}
@Override
public void focusLost(FocusEvent e) {
if(flag==false){ //if flag=false;
final JTextField tf= (JTextField) e.getComponent();
tf.select(-1, -1);
flag=true;}
}
});
}
public static void main(String[] args){
new cl();
}
@Override
public void mouseClicked(MouseEvent e) {
flag=false;
}
@Override
public void mousePressed(MouseEvent e) {
flag=false;
}
@Override
public void mouseReleased(MouseEvent e) {
flag=false;
}
@Override
public void mouseEntered(MouseEvent e) {
flag=false;
}
@Override
public void mouseExited(MouseEvent e) {
flag=false;
}
}
Upvotes: -1