21xrx.com
2024-11-05 14:43:36 Tuesday
登录
文章检索 我的文章 写文章
用Java Swing编写一个简单的计算器界面
2023-06-11 10:41:23 深夜i     --     --
Java Swing

我最近学习了Java的Swing库,这个库可以方便地编写GUI界面,于是我想写一个计算器界面来练手。下面是我的代码:


import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class Calculator extends JFrame implements ActionListener {

  private JTextField display;

  private double operand1, operand2;

  private String operator;

  private boolean waitingForOperand2;

  public Calculator() {

    super("Calculator");

    operand1 = 0;

    operand2 = 0;

    waitingForOperand2 = false;

    JPanel buttonPanel = new JPanel();

    buttonPanel.setLayout(new GridLayout(4, 4));

    String[] buttonLabels = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"};

    for (String label : buttonLabels) {

      JButton button = new JButton(label);

      button.addActionListener(this);

      buttonPanel.add(button);

    }

    display = new JTextField();

    display.setEditable(false);

    Container container = getContentPane();

    container.add(display, BorderLayout.NORTH);

    container.add(buttonPanel, BorderLayout.CENTER);

    setSize(300, 300);

    setVisible(true);

  }

  public static void main(String[] args) {

    Calculator calculator = new Calculator();

    calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  }

  public void actionPerformed(ActionEvent event) {

    String label = event.getActionCommand();

    if (label.equals("C")) {

      operand1 = 0;

      operand2 = 0;

      operator = null;

      waitingForOperand2 = false;

      display.setText("");

    } else if ("0123456789.".indexOf(label) >= 0) {

      if (waitingForOperand2) {

        display.setText("");

        waitingForOperand2 = false;

      }

      display.setText(display.getText() + label);

    } else {

      if (!waitingForOperand2) {

        waitingForOperand2 = true;

        operand1 = Double.parseDouble(display.getText());

        operator = label;

      } else {

        operand2 = Double.parseDouble(display.getText());

        double result = evaluate();

        display.setText(Double.toString(result));

        operand1 = result;

        operator = label;

      }

    }

  }

  private double evaluate() {

    if (operator.equals("+")) {

      return operand1 + operand2;

    } else if (operator.equals("-"))

      return operand1 - operand2;

     else if (operator.equals("*")) {

      return operand1 * operand2;

    } else if (operator.equals("/"))

      return operand1 / operand2;

     else

      return 0;

    

  }

}

这个计算器界面比较简单,只支持四则运算和小数点。我使用了GridLayout布局,将16个按钮放在了一个4x4的矩阵中。点击按钮时,我使用了ActionListener来处理事件。我使用了一个字符串变量operator来存储运算符,一个布尔变量waitingForOperand2来标记是否正在等待输入第二个操作数,以及两个双精度浮点数变量operand1和operand2来存储操作数。

三个 ,GUI,计算器。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复