如果我的问题不是很具体,这是我正在尝试做的。我有一个计算器,它有两个JTextField,一个JLabel(“Answer =”)和一个JTextField作为答案。用JButton添加文本到两个文本框
我有一个JButtons(0到9)的数组,允许用户点击它们将数字添加到JTextField中,并将光标在其中激活......这是这里的问题。我只能有两个文本字段中的一个向其添加数字,或者两者都添加相同的数字。
例如,如果我点击一个按钮并且addActionListener
设置为(new AddDigitsONE)
它只会允许我将数字添加到第一个JTextField。即使我尝试将游标设置为第二个JTextField并使用JButton添加数字,它也会跳回到第一个JTextField。
代码添加Jbutton将数组到的JPanel JFrame中
// 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));
}
}
有没有办法合并这两个动作的听众和区分它们之间的文本字段中有光标激活(同时让我输入数字在两个使用JButton的JTextFields中)?
这似乎是一个非常尴尬的方式来制作一个计算器,至少对我来说。 – Max 2012-01-06 20:04:18
@Max我知道。我正在研究一些制作计算器的更复杂的方法。防爆。有一个文本框显示您的所有数字和操作......类似于一个真实的计算器。但是他们中的很多人都有点过头了。 – Rob 2012-01-06 20:06:16