⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 calculatorframe.java

📁 用java编的简单的计算器
💻 JAVA
字号:
//【例6.2】  计算器程序雏形。

import java.awt.*;
import java.awt.event.*;

public class CalculatorFrame extends Frame implements ActionListener
{
    private TextField text;
    private Button button_1,button_2,button_plus,button_cancel;

    public CalculatorFrame()
    {
        super("Calculator");
        
        this.setSize(320,120);
        this.setBackground(Color.lightGray);
        this.setLocation(300,240);
        this.setLayout(new FlowLayout(FlowLayout.LEFT));  //流布局且左对齐
        
        text = new TextField(40);
        text.setEditable(false);                 //只能显示,不允许编辑
        this.add(text);

        button_1 = new Button("1");
        button_2 = new Button("2");
        button_plus = new Button("+");
        button_cancel = new Button("C");

        this.add(button_1);
        this.add(button_2);
        this.add(button_plus);
        this.add(button_cancel);

        button_1.addActionListener(this);        //为按钮注册单击事件监听器
        button_2.addActionListener(this);
        button_plus.addActionListener(this);
        button_cancel.addActionListener(this);
        
        this.addWindowListener(new WinClose());  //为框架注册窗口事件监听器,委托WinClose类的对象处理事件
        this.setVisible(true);
    }

    public void actionPerformed(ActionEvent e)   //按钮的单击事件处理方法
    {                                            //实现ActionListener接口中的方法
        if (e.getSource()==button_cancel)        //获得产生事件的对象
            text.setText("");
        else                                     //获取按钮标签,重新设置文本内容
            text.setText(text.getText()+e.getActionCommand());
    }
    
    public static void main(String arg[])
    {
        new CalculatorFrame();
    }
}


class WinClose implements WindowListener
{
    public void windowClosing(WindowEvent e)     //单击窗口关闭按钮时触发并执行
    {                                            //实现WindowListener接口中的方法
        System.exit(0);                          //结束程序运行
    }

    public void windowOpened(WindowEvent e)         {  }
    public void windowActivated(WindowEvent e)      {  }
    public void windowDeactivated(WindowEvent e)    {  }
    public void windowClosed(WindowEvent e)         {  }
    public void windowIconified(WindowEvent e)      {  }
    public void windowDeiconified(WindowEvent e)    {  }
}

/*
或者
class WinClose extends WindowAdapter             //继承适配类
{
    public void windowClosing(WindowEvent e)     //单击窗口关闭按钮时触发并执行
    {                                            //覆盖适配类WindowAdapter中的方法
        System.exit(0);                          //结束程序运行
    }
}
*/

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -