Java 将JTextField或JComboBox的光标移动到起始位置

Java 将JTextField或JComboBox的光标移动到起始位置,java,swing,cursor,jcombobox,jtextfield,Java,Swing,Cursor,Jcombobox,Jtextfield,我有一个带有一些文本的JTextField。单击文本字段时,光标移动到字段的末尾。我希望光标在聚焦时移动到字段的开头 我对可编辑的JComboBox也有同样的问题 如何在焦点上实现光标定位?我想这可能就是您想要的: JTextField t = new JTextField(); t.setHorizontalAlignment(JTextField.LEFT); 您可以使用此命令 组件设置CaretPosition(索引) 索引是插入符号位置。我的意思是我有一个可编辑的JComboBox,内

我有一个带有一些文本的
JTextField
。单击文本字段时,光标移动到字段的末尾。我希望光标在聚焦时移动到字段的开头

我对可编辑的
JComboBox
也有同样的问题


如何在焦点上实现光标定位?

我想这可能就是您想要的:

JTextField t = new JTextField();
t.setHorizontalAlignment(JTextField.LEFT);

您可以使用此命令

组件设置CaretPosition(索引)


索引是插入符号位置。

我的意思是我有一个可编辑的JComboBox,内容中有任何文本,当我单击JComboBox时,我会将标记移动到可编辑JComboBox的开头。默认情况下,它会转到文本字段的末尾。当我说字段开始时,我不是指下拉列表的第一项。谢谢你的澄清。在编辑该评论的过程中,我的困惑有所缓解
/**
* 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.