5

我正在制作一个计算器来测试我的 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);
    }
}

截图

4

4 回答 4

2

为了省去很多麻烦,if-else您可以创建一个 s 数组JButton并循环遍历它们。
所以按钮 0 将在索引 0 处。

然后,您可以将文本附加到JTextFieldas:

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

于 2013-05-10T14:36:32.813 回答
2

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

in.setText(in.getText() + num)代替in.setText("" + num)

于 2013-05-10T14:36:51.340 回答
1

你应该追加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);

    }

}
于 2013-05-10T14:36:14.137 回答
0

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

    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同样,您可以为...添加其他按钮并像这样实现它。

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

于 2018-09-25T07:28:43.100 回答