21xrx.com
2024-11-22 12:28:50 Friday
登录
文章检索 我的文章 写文章
我最近在学习Java编程
2023-06-11 03:42:36 深夜i     --     --
Java 计算器 Swing库

我最近在学习Java编程,今天我想分享一个简单的Java计算器的代码。在我编写这个计算器时,我主要利用了Java中的Swing库来帮助构建GUI界面。下面是我的代码示例:


import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class SimpleCalculator implements ActionListener {

  JTextField textField;

  JButton[] buttons = new JButton[16];

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

  String firstNumber = "";

  String secondNumber = "";

  String operator = "";

  Double result = 0.0;

  public SimpleCalculator() {

    JFrame frame = new JFrame("简易计算器");

    frame.setLayout(new BorderLayout());

    frame.setSize(250, 300);

    frame.setLocationRelativeTo(null);

    textField = new JTextField();

    textField.setEditable(false);

    frame.add(textField, BorderLayout.NORTH);

    JPanel buttonPanel = new JPanel(new GridLayout(4, 4));

    for (int i = 0; i < 16; i++) {

      buttons[i] = new JButton(buttonLabels[i]);

      buttons[i].addActionListener(this);

      buttonPanel.add(buttons[i]);

    }

    frame.add(buttonPanel, BorderLayout.CENTER);

    frame.setVisible(true);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  }

  public static void main(String[] args) {

    SimpleCalculator calculator = new SimpleCalculator();

  }

  public void actionPerformed(ActionEvent e) {

    String command = e.getActionCommand();

    switch (command) {

      case "C":

        firstNumber = "";

        secondNumber = "";

        operator = "";

        result = 0.0;

        textField.setText("");

        break;

      case "+":

      case "-":

      case "*":

      case "/":

        operator = command;

        firstNumber = textField.getText();

        textField.setText("");

        break;

      case "=":

        secondNumber = textField.getText();

        Double num1 = Double.parseDouble(firstNumber);

        Double num2 = Double.parseDouble(secondNumber);

        switch (operator) {

          case "+":

            result = num1 + num2;

            break;

          case "-":

            result = num1 - num2;

            break;

          case "*":

            result = num1 * num2;

            break;

          case "/":

            result = num1 / num2;

            break;

          default:

            break;

        }

        textField.setText(result.toString());

        break;

      default:

        textField.setText(textField.getText() + command);

        break;

    }

  }

}

通过这个代码,我学会了如何创建一个简单的Java计算器。我还学到了如何使用Swing库来构建GUI界面,如何使用ActionListener来捕获用户的动作并根据用户的输入来执行一系列操作。这个计算器可以帮助我更好地理解Java编程的基础知识,我可以用它来练习其他编程技能。

  
  

评论区

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