使用JButton将文本添加到两个文本字段

如果我的问题不是很具体,那么我正在努力做到这一点。 我有一个计算器,有两个JTextFields,一个JLabel(“Answer =”)和一个JTextField作为答案。

我有一个JButtons(0到9)数组,允许用户点击它们将数字添加到JTextField,光标在其中激活…这是问题所在。 我只能将两个文本字段中的一个添加到它们中,或者两者都添加相同的数字。

例如,如果我单击一个按钮并且addActionListener设置为(new AddDigitsONE) ,它将只允许我向第一个JTextField添加数字。 即使在我尝试将光标设置为第二个JTextField并使用JButtons为其添加数字之后,它也会跳回到第一个JTextField。

用于将JButtons数组添加到JFrame中的JPanel的代码


 // input is my JPanel set to BorderLayout.SOUTH for (int i = 0; i < button.length; i++) { text = Integer.toString(i); button[i] = new JButton(); button[i].setText(text); input.add(button[i]); button[i].addActionListener(new AddDigitsONE()); } 

我的动作监听器的代码:第一个JTextField

 // firstNumber is my first JTextField // command is the button pressed (0-9) // command "<" is erasing one character at a time private class AddDigitsONE implements ActionListener { public void actionPerformed(ActionEvent e) { String text = firstNumber.getText(); String command = ((JButton)(e.getSource())).getText(); if (command == "<") { firstNumber.setText(text.substring(0,text.length()-1)); } else firstNumber.setText(text.concat(command)); } } 

我的动作监听器的代码:第二个JTextField

 private class AddDigitsTWO implements ActionListener { public void actionPerformed(ActionEvent e) { String text = secondNumber.getText(); String command = ((JButton)(e.getSource())).getText(); if (command == "<") { secondNumber.setText(text.substring(0,text.length()-1)); } else secondNumber.setText(text.concat(command)); } } 

有没有办法合并两个动作侦听器并区分哪个文本字段的光标处于活动状态(同时允许我使用JButtons在两个JTextFields中输入数字)?

您可以向按钮添加Action,而不是使用ActionListener。 在这种情况下,您需要扩展TextAction,因为它有一个方法,允许您获取最后一个聚焦文本组件,以便您可以将数字插入该组件。 代码如下:

 class AddDigit extends TextAction { private String digit; public AddDigit(String digit) { super( digit ); this.digit = digit; } public void actionPerformed(ActionEvent e) { JTextComponent component = getFocusedComponent(); component.replaceSelection( digit ); } }