I have a JTextField
with some text. When I click text field the cursor moves to the end of field. I want the cursor to move to the start of the field when it becomes focused.
I have the same problem with an editable JComboBox
.
How can I achieve this cursor positioning on focus?
JTextField text = new JTextField(); text. setBounds( 370 , 160 , 200 , 20 );
/**
* On gaining focus place the cursor at the start of the text.
*/
public class CursorAtStartFocusListener extends FocusAdapter {
@Override
public void focusGained(java.awt.event.FocusEvent evt) {
Object source = evt.getSource();
if (source instanceof JTextComponent) {
JTextComponent comp = (JTextComponent) source;
comp.setCaretPosition(0);
} else {
Logger.getLogger(getClass().getName()).log(Level.INFO,
"A text component expected instead of {0}",
source.getClass().getName());
}
}
}
jTextField1.addFocusListener(new CursorAtStartFocusListener());
jComboBox1.getEditor().getEditorComponent().addFocusListener(new CursorAtStartFocusListener());
// Only one instance of CursorAtStartFocusListener needed.
You can use this command
comp.setCaretPosition(index);
there index is caret position.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With