這些是做樣品按鈕,你要問什麼:
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);
}
來源
2014-10-18 13:09:23
Tom
這正是我所期待的。 現在我可以使用按鈕瀏覽texfield。 很多謝謝!構建計算器並需要使用鍵盤和按鈕編輯字段。謝謝 – JoshuaTree 2014-10-18 14:09:01