我在网上找到了很多解决方案,但没有一个适合我的问题。我在 JFrame
中有一个 KeyBoard,单击它时,它会写入另一个 JFrame
中的 JTextField
。
由于 JText
中的 OnClickEvent
,键盘出现,类似于 iphone 键盘。
如何将按钮链接到其他框架中的 JTextField
?
最佳答案
首先,您的 Swing 键盘需要知道将值传递到哪里。为它添加一个 JTextComponent 字段变量和一个 setter :
private JTextComponent textComponent;
JTextComponent 是 JTextField、JTextArea 等的基类...
然后您需要编写一个处理 Action 的 ActionListener:
private class KeyboardActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
JButton key = (JButton) e.getSource();
textComponent.getDocument().insertString(textComponent.getCaretPosition(), key.getText(), null);
} catch (BadLocationException ex) {
Logger.getLogger(KeyboardDialog.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
第三步是将所有按钮添加到该 Action 监听器。单击按钮时,它将从 ActionEvent 中获取按钮,并将其值插入当前的插入位置。请记住,这不会处理功能键。为此,请查看 JTextComponent .
关于java - 如何为触摸屏编程java虚拟键盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25059411/