Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move cursor of JTextField or JComboBox to the start

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?

like image 249
Karen Avatar asked Mar 31 '12 08:03

Karen


People also ask

How to set cursor position in JTextField in java?

JTextField text = new JTextField(); text. setBounds( 370 , 160 , 200 , 20 );


2 Answers

/**
* 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.
like image 167
Joop Eggen Avatar answered Oct 23 '22 09:10

Joop Eggen


You can use this command

comp.setCaretPosition(index);

there index is caret position.

like image 29
user1337052 Avatar answered Oct 23 '22 10:10

user1337052