如果我的問題不是很具體,這是我正在嘗試做的。我有一個計算器,它有兩個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