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



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

我对可编辑的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.

您可以使用此命令

comp.setCaretPosition(索引);

那里的索引是插入符号的位置。

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

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

最新更新