java - 添加同一按钮的多个实例

标签 java swing

我正在为学校作业创建一个简单的计算器,但无法让它计算多个数字

package calculator;

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Container;

public class Calculator implements ActionListener{

JFrame guiFrame;
JPanel buttonPanel;
JTextField numberCalc;
int calcOperation = 0;
int currentCalc;


public static void main(String[] args) {

     //Use the event dispatch thread for Swing components
     EventQueue.invokeLater(new Runnable()
     {

        @Override
         public void run()
         {

             new Calculator();         
         }
     });

}

public Calculator()
{
    guiFrame = new JFrame();

    //make sure the program exits when the frame closes
    guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    guiFrame.setTitle("Simple Calculator");
    guiFrame.setSize(300,300);

    //This will center the JFrame in the middle of the screen
    guiFrame.setLocationRelativeTo(null);

    numberCalc = new JTextField();
    numberCalc.setHorizontalAlignment(JTextField.RIGHT);
    numberCalc.setEditable(false);

    guiFrame.add(numberCalc, BorderLayout.NORTH);

    buttonPanel = new JPanel();

    //Make a Grid that has three rows and four columns
    buttonPanel.setLayout(new GridLayout(4,4));   
    guiFrame.add(buttonPanel, BorderLayout.CENTER);

    //Add the number buttons
    for (int i=1;i<10;i++)
    {
        addButton(buttonPanel, String.valueOf(i));
    }

    JButton addButton = new JButton("+");
    addButton.setActionCommand("+");

    OperatorAction subAction = new OperatorAction(1);
    addButton.addActionListener(subAction);

    JButton subButton = new JButton("-");
    subButton.setActionCommand("-");

    OperatorAction addAction = new OperatorAction(2);
    subButton.addActionListener(addAction);

    JButton multiplyButton = new JButton("*");
    multiplyButton.setActionCommand("*");

    OperatorAction multiAction = new OperatorAction(3);
    multiplyButton.addActionListener(multiAction);

        JButton divideButton = new JButton("/");
        divideButton.setActionCommand("/");

        OperatorAction diviAction = new OperatorAction(4);
        divideButton.addActionListener(diviAction);

        JButton clearButton = new JButton("ce");
        clearButton.setActionCommand("ce");

        OperatorAction clearAction = new OperatorAction(5);
        clearButton.addActionListener(clearAction);

        JButton blankButton = new JButton(" ");

    JButton equalsButton = new JButton("=");
    equalsButton.setActionCommand("=");
    equalsButton.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent event)
        {

            if (!numberCalc.getText().isEmpty())
            {
                int number = Integer.parseInt(numberCalc.getText()); 

                if (calcOperation == 1)
                {
                    int calculate = currentCalc  + number;
                    numberCalc.setText(Integer.toString(calculate));
                }
                if (calcOperation == 2)
                {
                    int calculate = currentCalc  - number;
                    numberCalc.setText(Integer.toString(calculate));
                }

                if (calcOperation == 3)
                {
                        int calculate = currentCalc * number;
                        numberCalc.setText(Integer.toString(calculate));
                }

                if (calcOperation == 4)
                {
                        int calculate = currentCalc / number;
                        numberCalc.setText(Integer.toString(calculate));
                }

                if (calcOperation == 5)
                {
                        int calculate = 0;
                        numberCalc.setText(Integer.toString(calculate));
                }
            }
        }
    });

    buttonPanel.add(addButton);
    buttonPanel.add(subButton);
    buttonPanel.add(equalsButton);
    buttonPanel.add(divideButton);
    buttonPanel.add(multiplyButton);
    buttonPanel.add(clearButton);
    buttonPanel.add(blankButton);
    guiFrame.setVisible(true);  
}

//All the buttons are following the same pattern
//so create them all in one place.
private void addButton(Container parent, String name)
{
    JButton but = new JButton(name);
    but.setActionCommand(name);
    but.addActionListener(this);
    parent.add(but);
}

//As all the buttons are doing the same thing it's
//easier to make the class implement the ActionListener
//interface and control the button clicks from one place
@Override
public void actionPerformed(ActionEvent event)
{
    //get the Action Command text from the button
    String action = event.getActionCommand();

    //set the text using the Action Command text
    numberCalc.setText(action);       
}

private class OperatorAction implements ActionListener
{
    private int operator;

    public OperatorAction(int operation)
    {
        operator = operation;
    }

    public void actionPerformed(ActionEvent event)
    {
        currentCalc = Integer.parseInt(numberCalc.getText()); 
        calcOperation = operator;
    }
  }
 }

但是,当我运行代码时,它不允许我输入超过一位数字的数字。另外,我创建的 ce 按钮不会重置为零。

我已经包含了输出的图像。 提前致谢。 Output of calculator

最佳答案

ActionListener 不正确

@Override
public void actionPerformed(ActionEvent event)
{
    //get the Action Command text from the button
    String action = event.getActionCommand();

    //set the text using the Action Command text
    numberCalc.setText(action);       
}

这会将 numberCalc 文本设置为按钮的值,而不是附加该值。

使用 numberCalc.setText(NumberCalc.getText() + action); 附加文本

此外,对于 OperatorAction,您无需更新任何 GUI 组件

public void actionPerformed(ActionEvent event)
{
    currentCalc = Integer.parseInt(numberCalc.getText()); 
    calcOperation = operator;
}

您应该清除numberCalc以等待下一个值,否则您最终会得到1 + 12而不是1 + 2

如果按钮是clearButton,则需要更改逻辑并重置所有内容currentCalcnumberCalccalcOperation,...

关于java - 添加同一按钮的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47307178/

相关文章:

java - 通用容器的通用工厂

Java 显示带有格式化字符串的 Jlabel.setText

java - OpenHFT Chronicle Map 内存分配和限制

java - 在 Play Framework 2.0.1 中访问 scala 模板内子实体的属性时出现问题

java - 如何获取从 1 开始到 n 结束的 String ?

java - 调整窗口上的 ImageIcon 大小

java - 如何用Java制作一个图 block

Java Swing getRootPane() 返回 null

java - 最小化和最大化 Java Swing 中自定义事件的 JFrame

java - 如何在 Java 上使用 hasNextInt 确保输入是整数