21xrx.com
2024-11-22 09:54:20 Friday
登录
文章检索 我的文章 写文章
Java GUI程序实例:简易计算器
2023-06-12 04:28:14 深夜i     --     --
Java GUI 计算器

在Java中,我们可以很容易地创建一个简易的计算器界面,使用户可以通过可视化界面来进行数学计算。本文将为大家介绍如何利用Java图形化应用程序界面(GUI)来实现一个简易的计算器,并提供相应的代码示例。

首先,我们需要创建一个包含各种数字操作按钮和运算符的网格布局。为此,我们可以使用Java的Swing库来创建按钮,包括数字按钮、运算符按钮和清楚按钮等。

代码示例:


import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class Calculator extends JFrame implements ActionListener {

  private JTextField textField;

  private JButton[] buttons = new JButton[16];

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

  public Calculator() {

    super("简易计算器");

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setPreferredSize(new Dimension(250, 250));

    setResizable(false);

    setLayout(new BorderLayout());

    textField = new JTextField();

    textField.setFont(new Font("Arial", Font.BOLD, 20));

    add(textField, BorderLayout.NORTH);

    JPanel buttonPanel = new JPanel();

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

    for (int i = 0; i < buttons.length; i++) {

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

      buttons[i].setFont(new Font("Arial", Font.BOLD, 18));

      buttons[i].addActionListener(this);

      buttonPanel.add(buttons[i]);

    }

    add(buttonPanel, BorderLayout.CENTER);

    pack();

    setLocationRelativeTo(null);

    setVisible(true);

  }

  public void actionPerformed(ActionEvent e) {

    String action = e.getActionCommand();

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

      textField.setText("");

    } else if (action.equals("=")) {

      String expression = textField.getText();

      try {

        String result = String.valueOf(eval(expression));

        textField.setText(result);

      } catch (Exception ex) {

        textField.setText("错误的表达式!");

      }

    } else {

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

    }

  }

  public static double eval(final String expression) {

    return new Object(){

      int pos = -1, ch;

      void nextChar() {

        ch = (++pos < expression.length()) ? expression.charAt(pos) : -1;

      }

      boolean eat(int charToEat) {

        while (ch == ' ') nextChar();

        if (ch == charToEat) {

          nextChar();

          return true;

        }

        return false;

      }

      double parse() {

        nextChar();

        double x = parseExpression();

        if (pos < expression.length()) throw new RuntimeException("未处理完的表达式" + expression.substring(pos));

        return x;

      }

      double parseExpression() {

        double x = parseTerm();

        for (;;) {

          if (eat('+')) x += parseTerm();

          else if (eat('-')) x -= parseTerm();

          else return x;

        }

      }

      double parseTerm() {

        double x = parseFactor();

        for (;;) {

          if (eat('*')) x *= parseFactor();

          else if (eat('/')) x /= parseFactor();

          else return x;

        }

      }

      double parseFactor() {

        if (eat('+')) return parseFactor();

        if (eat('-')) return -parseFactor();

        double x;

        int startPos = this.pos;

        if (eat('(')) {

          x = parseExpression();

          eat(')');

        } else if ((ch >= '0' && ch <= '9') || ch == '.') {

          while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();

          x = Double.parseDouble(expression.substring(startPos, this.pos));

        } else if (ch >= 'a' && ch <= 'z') {

          while (ch >= 'a' && ch <= 'z') nextChar();

          String func = expression.substring(startPos, this.pos);

          x = parseFactor();

          if (func.equals("sqrt")) x = Math.sqrt(x);

          else if (func.equals("sin")) x = Math.sin(Math.toRadians(x));

          else if (func.equals("cos")) x = Math.cos(Math.toRadians(x));

          else if (func.equals("tan")) x = Math.tan(Math.toRadians(x));

          else throw new RuntimeException("未知函数:" + func);

        } else {

          throw new RuntimeException("未知字符: " + (char)ch);

        }

        if (eat('^')) x = Math.pow(x, parseFactor());

        return x;

      }

    }.parse();

  }

}

在上面的代码中,我们首先创建了一个JFrame窗口,并添加了一个JTextField文本框。此外,我们还创建了一个包含数字和运算符按钮的JPanel面板,并将其添加到窗口的中心。每个按钮都具有自己的监听器,并为其添加了ActionListener接口。最后,我们使用Gridlayout来实现网格布局,将按钮添加到面板中。

在此,我们还使用了一个JavaScript函数来解析算术表达式。此函数使用递归算法来解析算术表达式,并返回结果。

接下来,我们创建一个main方法来启动我们的应用程序:


public static void main(String[] args) {

  new Calculator();

}

现在,我们可以运行以上代码,看看我们的GUI计算器是如何运行的。

  
  

评论区

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