【发布时间】:2012-02-04 12:40:52
【问题描述】:
如果我的问题不是很具体,这就是我想要做的。我有一个计算器,它有两个 JTextField、一个 JLabel ("Answer = ") 和一个 JTextField 作为答案。
我有一个 JButtons 数组(0 到 9),允许用户单击它们以将数字添加到 JTextField 中,其中光标处于活动状态......这是这里的问题。我只能让两个文本字段中的一个向它们添加数字,或者两者都相互添加相同的数字。
例如,如果我单击一个按钮并将addActionListener 设置为(new AddDigitsONE),它将只允许我向第一个JTextField 添加数字。即使在我尝试将光标设置到第二个 JTextField 并使用 JButton 向其添加数字之后,它也会跳回第一个 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));
}
}
有没有办法合并两个动作侦听器并区分哪个文本字段中的光标处于活动状态(同时允许我使用 JButton 在两个 JTextField 中输入数字)?
【问题讨论】:
-
至少对我来说,这似乎是一种非常尴尬的制作计算器的方式。
-
@Max 我知道。我正在研究制作计算器的一些更复杂的方法。前任。有一个文本字段来显示你所有的数字和操作......类似于一个真正的计算器。但其中很多都让我有点不知所措。
标签: java swing actionlistener jtextfield calculator