这些是做样品按钮,你要问什么:
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