21xrx.com
2025-07-16 16:46:13 Wednesday
文章检索 我的文章 写文章
Java GUI应用:简易计算机代码实现
2023-06-14 07:44:06 深夜i     8     0

在Java中,可以通过使用Graphical User Interface(GUI)实现简易计算机应用程序。下面是一个简单的Java代码示例,演示如何使用GUI元素创建一个基本的计算机程序:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleCalculator implements ActionListener {
  // GUI元素
  JTextField textField1, textField2, textField3;
  JButton addButton, subButton, mulButton, divButton;
  // 构造函数
  SimpleCalculator() {
    // 创建JFrame对象
    JFrame frame = new JFrame("Simple Calculator");
    // 创建文本框
    textField1 = new JTextField(10);
    textField2 = new JTextField(10);
    textField3 = new JTextField(10);
    // 创建按钮
    addButton = new JButton("+");
    subButton = new JButton("-");
    mulButton = new JButton("*");
    divButton = new JButton("/");
    // 添加事件监听器
    addButton.addActionListener(this);
    subButton.addActionListener(this);
    mulButton.addActionListener(this);
    divButton.addActionListener(this);
    // 创建面板并添加元素
    JPanel panel = new JPanel();
    panel.add(textField1);
    panel.add(textField2);
    panel.add(addButton);
    panel.add(subButton);
    panel.add(mulButton);
    panel.add(divButton);
    panel.add(textField3);
    // 设置基本属性
    frame.add(panel);
    frame.setSize(300, 150);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
  public void actionPerformed(ActionEvent e) {
    // 获取输入值
    int a = Integer.parseInt(textField1.getText());
    int b = Integer.parseInt(textField2.getText());
    // 进行操作
    int result = 0;
    if (e.getSource() == addButton) {
      result = a + b;
    } else if (e.getSource() == subButton)
      result = a - b;
     else if (e.getSource() == mulButton) {
      result = a * b;
    } else if (e.getSource() == divButton)
      result = a / b;
    
    // 显示结果
    textField3.setText(String.valueOf(result));
  }
  public static void main(String[] args) {
    SimpleCalculator calc = new SimpleCalculator();
  }
}

在这个例子中,我们使用了Swing库的一些元素来创建一个GUI。我们首先创建了一个JFrame对象,向其添加了一个面板。面板上包括三个文本框和四个按钮,每个按钮代表不同的操作。我们添加了一个ActionListener,以便在用户单击按钮时执行操作。最后,我们将计算结果显示在第三个文本框中。

下面是关键词:

1. Java GUI

2. 计算器应用程序

3. ActionListener

  
  

评论区