将JTextField或JComboBox的光标移动到开头

5

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

我在可编辑的JComboBox中也遇到了同样的问题。

我如何实现在获得焦点时进行光标定位?


1
我的意思是,我有一个可编辑的JComboBox,其中包含任何文本内容,当我单击JComboBox时,我希望将标记移动到可编辑JComboBox的开头。默认情况下,它会移到文本字段的末尾。当我说字段的开头时,我并不是指下拉列表的第一项。 - Karen
感谢您的澄清。在编辑该评论时,我的困惑有所消除。 :) - Andrew Thompson
3个回答

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.

2

您可以使用以下命令:

comp.setCaretPosition(index);

其中,index 是光标位置。


0
我认为这可能是你在找的东西:
JTextField t = new JTextField();
t.setHorizontalAlignment(JTextField.LEFT);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接