繁体   English   中英

Java 计算器向文本字段添加数字

[英]Java calculator add numbers to textfield

我正在制作一个计算器来测试我的 Java 技能。 如何让数字显示在 jTextfield 中,直到我按下一个按钮来计算数字; 我希望每个数字都显示在文本字段中。 例如,如果我按 1 和零,我希望文本字段有 10。

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);
    }
}

截图

为了省去很多if-else的麻烦,您可以创建一个JButton数组并循环遍历它们。
所以按钮 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;
    }
}

这是 Oracle 关于此主题的教程: http : //docs.oracle.com/javase/tutorial/uiswing/components/textfield.html

您想将文本附加到已经存在的任何内容 - 尝试类似

in.setText(in.getText() + num)而不是in.setText("" + num)

你应该附加in.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);

    }

}

您可以将ActionListener添加到数字按钮。 例如:如果你有一个JButton b11添加到文本字段......你可以像这样使用它:

    public void actionPerformed(ActionEvent e) {
        /* I'm using equals method because I feel that it is more reliable than '==' operator
         * but you can also use '=='
         */
        if(e.getSource().equals(b1){
            in.setText(in.getText + "1");
        }
    }

同样,您可以为1,2,3添加其他按钮......并像这样实现它。

希望对你有帮助.... :-) :-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM