How can I make a component ( JTextField
, JFormattedTextField
and others) when clicked / gain focus, position the cursor in the 0
position of the component, especially when the component is already filled and the user clicks on it again? I'm trying to use setCaretPosition(0);
What I've tried:
package geral;
import java.awt.Dimension;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.MaskFormatter;
public class SetaPosicao extends JFrame implements FocusListener {
private final JTextField campo = new JTextField();
private final JFormattedTextField campo2 = new JFormattedTextField();
public static void main(String[] args) {
SetaPosicao tela = new SetaPosicao();
tela.setVisible(true);
}
public SetaPosicao() {
add(colocaCampo());
setSize(500, 150);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
MaskFormatter mf = new MaskFormatter("#####-###");
mf.install(campo2);
} catch (Exception e) {
}
}
private JComponent colocaCampo() {
JPanel painel = new JPanel();
JLabel label = new JLabel("TextField");
JLabel label2 = new JLabel("Formatted");
painel.add(label);
painel.add(campo);
campo.setPreferredSize(new Dimension(120, 22));
//campo.setCaretPosition(0);
painel.add(label2);
painel.add(campo2);
campo2.setPreferredSize(new Dimension(80, 22));
//campo2.setCaretPosition(0);
return painel;
}
@Override
public void focusGained(FocusEvent e) {
campo.setCaretPosition(0);
campo2.setCaretPosition(0);
}
@Override
public void focusLost(FocusEvent e) {
}
}