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); comp.selectAll(); } } }jComboBox.getEditor().getEditorComponent().addFocusListener(new
CursorAtStartFocusListener());
As you see from code above I want to select all text in editable JComboBox and set cursor position to the start.
But I have problem if I first write comp.setCaretPosition(0) then comp.selectAll(), the text is selected but cursor is on the end of text, otherwise if I first write comp.selectAll() then comp.setCaretPosition(0), I get cursor in position that I want but text isn’t selected.
Have any idea how can I do this thing?
CaretandselectAllis better to wrapping intoinvokeLater, but forJTextComponent(you can derive that fromJComboBoxtoo) you have to decide if you want to useselectAll()or use
Caret(fromDocument)EDIT
1) for editable
JComboBox2) or derive
JTextFieldorJFormattedTextFieldfrom editableJComboBoxthen add FocusListener e.g.
EDIT 2 :
SSCCE for editable JComboBox,
EDIT 3.
dirty hack could be