2014-10-18 97 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