Java计算器将数字添加到文本字段
我正在做一个计算器来测试我的java技能。如何使数字显示在jTextfield中,直到我按下一个按钮来计算数字;我希望每个数字都显示在文本字段中。例如,如果我按下1和0,我希望文本字段有10Java计算器将数字添加到文本字段,java,button,textfield,calculator,Java,Button,Textfield,Calculator,我正在做一个计算器来测试我的java技能。如何使数字显示在jTextfield中,直到我按下一个按钮来计算数字;我希望每个数字都显示在文本字段中。例如,如果我按下1和0,我希望文本字段有10 int num; JTextField in = new JTextField(20); // input field where numbers will up; public void actionPerformed(ActionEvent e) { if (e.getSource() ==
int num;
JTextField in = new JTextField(20); // input field where numbers will up;
public void actionPerformed(ActionEvent e) {
if (e.getSource() == bouttons.get(0)) {
num = 0;
in.setText("" + num);
}
if (e.getSource() == bouttons.get(1)) {
int num = 1;
in.setText("" + num);
}
}
您应该在.getText()中附加
,
而不是空字符串
int num ;
JTextField in = new JTextField(20); // input field where numbers will up;
public void actionPerformed(ActionEvent e) {
if (e.getSource() == bouttons.get(0)) {
num =0;
in.setText(in.getText() + num);
}
if (e.getSource() == bouttons.get(1)) {
int num = 1;
in.setText(in.getText() + num);
}
}
为了省去大量的
if-else
的麻烦,您可以创建一个JButton
s数组,并在循环中遍历它们。所以按钮0将位于索引0处 然后,您可以将文本附加到
JTextField
,如下所示:
String alreadyDisplayed = in.getText(); //get the existing text
String toDisplay = alreadyDisplayed + Integer.toString(loopCounter);// append the position to the text
in.setText(toDisplay);// display the text
您可以按如下方式循环:
for(int i=0;i<jbuttonArray.length;i++){
if(e.getSource()==jbuttonArray[i]){
//insert above code here;
}
}
for(int i=0;i您想将文本附加到任何已经存在的内容上,请尝试以下操作
in.setText(in.getText()+num)
而不是in.setText(“+num)
您可以将ActionListener
添加到数字按钮。例如:如果您有一个JButton b1
将1
添加到文本字段…您可以这样使用它:
public void actionPerformed(ActionEvent e){
/*我使用equals方法是因为我觉得它比“==”运算符更可靠
*但您也可以使用“==”
*/
如果(e.getSource())等于(b1){
in.setText(in.getText+“1”);
}
}
类似地,您可以为1,2,3
添加其他按钮,并像这样实现它
希望这能帮助你……:-):-)你能分享完整的代码吗。似乎您没有添加文本请参阅以获取提示。