2014-10-18 103 views
1

我真的很努力地找到功能(如果它存在), 通過單擊Button來移動JTextFields光標,而不是使用鼠標。JTextField - 使用按鈕移動光標

例如,我有我的文本字段添加了一個字符串。 通過單擊後退按鈕,光標將一次或一次向後移動通過字符串,1個位置,具體取決於按下哪個按鈕。

我可以用鼠標點擊它,只需點擊並鍵入,但實際上我需要讓它具有按鈕,以便用戶可以選擇使用鍵盤輸入名稱,或者只需點擊進入JTextArea並輸入。

可能嗎?如果是的話,我應該尋找什麼方法。

謝謝。

回答

3

這些是做樣品按鈕,你要問什麼:

btnMoveLeft = new JButton("-"); 
btnMoveLeft.setFocusable(false); 
btnMoveLeft.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent arg0) { 
    txtAbc.setCaretPosition(txtAbc.getCaretPosition() - 1); // move the carot one position to the left 
    } 
}); 
// omitted jpanel stuff 

btnmoveRight = new JButton("+"); 
btnmoveRight.setFocusable(false); 
btnmoveRight.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
    txtAbc.setCaretPosition(txtAbc.getCaretPosition() + 1); // move the carot one position to the right 
    } 
}); 
// omitted jpanel stuff 

它們在文本框txtAbc每點擊1個位置移動carot。請注意,您需要禁用兩個按鈕的focusable標誌,否則如果您單擊其中一個按鈕並且無法再看到該標誌,則文本框的焦點將會消失。

爲了避免異常,如果你想移動的carot出來的文本框邊界(-1或大於文本長度大),你應該檢查新值(例如,在專用的方法):

private void moveLeft(int amount) { 
    int newPosition = txtAbc.getCaretPosition() - amount; 
    txtAbc.setCaretPosition(newPosition < 0 ? 0 : newPosition); 
} 

private void moveRight(int amount) { 
    int newPosition = txtAbc.getCaretPosition() + amount; 
    txtAbc.setCaretPosition(newPosition > txtAbc.getText().length() ? txtAbc.getText().length() : newPosition); 
} 
+0

這正是我所期待的。 現在我可以使用按鈕瀏覽texfield。 很多謝謝!構建計算器並需要使用鍵盤和按鈕編輯字段。謝謝 – JoshuaTree 2014-10-18 14:09:01