5

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?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Karen
  • 1,025
  • 1
  • 10
  • 22
  • 1
    I mean I have editable JComboBox with any text in content , and when I click JComboBox I wnat to move marker to the start of editable JComboBox. By default it goes to the end of text field. When I said start of field I don't mean first item of drop down list. – Karen Mar 31 '12 at 09:27
  • Thanks for clarifying. My confusion became sorted somewhat throughout the editing of that comment. :) – Andrew Thompson Mar 31 '12 at 09:30

3 Answers3

5
/**
* 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.
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
2

You can use this command

comp.setCaretPosition(index);

there index is caret position.

user1337052
  • 181
  • 1
  • 4
0

I think this may be what you're looking for:

JTextField t = new JTextField();
t.setHorizontalAlignment(JTextField.LEFT);
gorn
  • 8,097
  • 5
  • 37
  • 44