Java Swing 简单计算器实现 - 使用 FlowLayout 布局

本教程将指导您使用 Java Swing 编写一个简单的计算器应用程序。该应用程序使用 FlowLayout 布局并包含加、减、乘、除四个运算按钮和三个文本框。

1. 实验要求

编写一个应用程序,有一个标题为'计算'的窗口,窗口的布局为 FlowLayout 布局。

设计四个按钮,分别命名为'加'、'减'、'乘'、'除';

另外,窗口中还有三个文本框。单击相应的按钮,将两个文本框的数字做运算,在第三个文本框中显示结果。

2. 实验指导

public class SetCalculator extends Frame implements ActionListener {
    static SetCalculator frm = new SetCalculator();
    static Button btn1,btn2,btn3,btn4;
    static TextField txt1,txt2,txt3;
    
    public static void main(String[] args) {
        frm.setTitle('计算器');
        frm.setBounds(300, 300, 300, 200);
        frm.setLayout(new FlowLayout());
        frm.setVisible(true);
        
        btn1 = new Button('加');
        btn2 = new Button('减');
        btn3 = new Button('乘');
        btn4 = new Button('除');
        btn1.addActionListener(frm);
        btn2.addActionListener(frm);
        btn3.addActionListener(frm);
        btn4.addActionListener(frm);
        
        txt1 = new TextField(10);
        txt2 = new TextField(10);
        txt3 = new TextField(10);
        txt3.setEditable(false);
        
        frm.add(txt1);
        frm.add(txt2);
        frm.add(txt3);
        frm.add(btn1);
        frm.add(btn2);
        frm.add(btn3);
        frm.add(btn4);
    }
    
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==btn1) {
            int sum;
            sum=Integer.parseInt(txt1.getText())+Integer.parseInt(txt2.getText());
            String Sum=String.valueOf(sum);
            txt3.setText(Sum);
        }
        if(e.getSource()==btn2) {
            int sum;
            sum=Integer.parseInt(txt1.getText())-Integer.parseInt(txt2.getText());
            String Sum=String.valueOf(sum);
            txt3.setText(Sum);
        }
        if(e.getSource()==btn3) {
            int sum;
            sum=Integer.parseInt(txt1.getText())*Integer.parseInt(txt2.getText());
            String Sum=String.valueOf(sum);
            txt3.setText(Sum);
        }
        if(e.getSource()==btn4) {
            double sum;
            sum=Double.parseDouble(txt1.getText())/Double.parseDouble(txt2.getText());
            String Sum=String.valueOf(sum);
            txt3.setText(Sum);
        }
    }
}

代码解释

  1. 类定义: SetCalculator 类继承自 Frame 类并实现 ActionListener 接口。
  2. 静态成员: 定义了四个按钮 (btn1btn4) 和三个文本框 (txt1txt3),并使用 static 关键字将其声明为静态成员,以便在整个程序中访问。
  3. main 方法: 该方法是程序的入口点。在 main 方法中,我们设置窗口标题、大小、布局和可见性。然后,我们创建按钮和文本框,并添加事件监听器到按钮上。
  4. actionPerformed 方法: 该方法是 ActionListener 接口中的一个方法,当按钮被点击时会触发。该方法首先获取触发事件的按钮,然后根据按钮的类型执行相应的运算并更新结果文本框。

总结

本教程演示了如何使用 Java Swing 编写一个简单的计算器应用程序。该应用程序使用 FlowLayout 布局,并包含了基本的加、减、乘、除运算功能。你可以根据需要扩展此应用程序,添加更多功能,例如科学计算功能、历史记录功能等。

Java Swing 简单计算器实现 - 使用 FlowLayout 布局

原文地址: https://www.cveoy.top/t/topic/oMqP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录