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(index);

インデックスはカレットの位置です。

于 2012-04-16T19:04:57.907 に答える
0

私はこれがあなたが探しているものかもしれないと思います:

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