21xrx.com
2024-11-05 18:50:32 Tuesday
登录
文章检索 我的文章 写文章
Java简易计算机设计:利用GUI实现计算器功能
2023-06-16 11:26:32 深夜i     --     --
Java 计算器 GUI

在Java中,我们可以通过GUI实现一个简易的计算器,让用户能够通过图形化界面实现各种基本运算。本文将提供一个Java计算器代码案例,详细介绍如何通过Java语言设计一个简单的计算器。

运用Java Swing包提供的组件,我们可以快速创建一个简单的图形用户界面,并实现计算器的基本功能。

代码案例:


import javax.swing.*;

import java.awt.*;

public class Calculator extends JFrame {

  private JPanel panel1;

  private JTextField textField1;

  private JButton button0;

  private JButton button1;

  private JButton button2;

  private JButton button3;

  private JButton button4;

  private JButton button5;

  private JButton button6;

  private JButton button7;

  private JButton button8;

  private JButton button9;

  private JButton buttonPoint;

  private JButton plus;

  private JButton multiply;

  private JButton divide;

  private JButton subtract;

  private JButton equals;

  private double firstNumber = 0;

  private String operation = "";

  public Calculator() {

    super("计算器");

    setContentPane(panel1);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    pack();

    setVisible(true);

    button0.addActionListener(e -> {

      textField1.setText(textField1.getText() + "0");

    });

    button1.addActionListener(e -> {

      textField1.setText(textField1.getText() + "1");

    });

    // 下同省略...

    plus.addActionListener(e -> {

      firstNumber = Double.parseDouble(textField1.getText());

      operation = "+";

      textField1.setText("");

    });

    equals.addActionListener(e -> {

      double secondNumber = Double.parseDouble(textField1.getText());

      double result = 0;

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

        result = firstNumber + secondNumber;

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

        result = firstNumber - secondNumber;

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

        result = firstNumber * secondNumber;

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

        result = firstNumber / secondNumber;

      

      textField1.setText(String.valueOf(result));

    });

  }

  public static void main(String[] args) {

    new Calculator();

  }

}

在这个代码案例中,我们运用了Java Swing提供的组件,包括JPanel、JTextField、JButton等等,实现了计算器的基本功能,包括加减乘除以及小数点运算等等。

三个

  
  

评论区

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