5

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

我对可编辑的JComboBox.

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

4

3 回答 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.
于 2012-03-31T09:24:40.337 回答
2

你可以使用这个命令

comp.setCaretPosition(索引);

索引是插入符号位置。

于 2012-04-16T19:04:57.907 回答
0

我认为这可能是您正在寻找的:

JTextField t = new JTextField();
t.setHorizontalAlignment(JTextField.LEFT);
于 2012-03-31T08:50:28.687 回答