2
How can I make a component (JTextField
, JFormattedTextField
and others) when being clicked/gaining focus, position the cursor in the position 0
component, especially when the component is already filled and the user clicks on it again? I am trying to use the setCaretPosition(0);
What I tried to:
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) {
}
}
what’s the difference between using Jcomponent and Jtextcomponent ? I can use in Jcomponent ?
– Java
@Java Jcomponent is the class that almost all swing components inherit, it is too Generic for the purpose of the question and lacks the method
setcaretposition
, After all, neither jpanel nor jlabel (which also inherit it) have text control such as jtextfield. Jtextcomponent is inherited by jtextfield and its subcomponents (such as jformatterdtextfield), and has text control methods for these fields, is the most recommended.– user28595
@Java not to mention that your Jcomponent is a container that you are adding a lot of fields, not just the two of text.
– user28595
thank you, it was very clear !
– Java