📄 calculator.java
字号:
//java简易计算机——
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class calculator extends WindowAdapter implements ActionListener //extends用与继承类,implements用于实现接口
{
static int a;
JFrame f;
JButton b[]=new JButton[10];
JButton ba; //加法
JButton bs; //减法
JButton bm; //乘法
JButton bd; //除法
JButton be; //等号
JButton bc; //清空
JTextField answer;
JPanel p;
String s="";
double t1,t2;
public static void main(String args[])
{
calculator cg=new calculator();
cg.go();
}
public void go()
{
p=new JPanel();
answer=new JTextField("0",30);
b[0]=new JButton("0");
b[1]=new JButton("1");
b[2]=new JButton("2");
b[3]=new JButton("3");
b[4]=new JButton("4");
b[5]=new JButton("5");
b[6]=new JButton("6");
b[7]=new JButton("7");
b[8]=new JButton("8");
b[9]=new JButton("9");
ba=new JButton("+");
bs=new JButton("-");
bm=new JButton("×");
bd=new JButton("÷");
be=new JButton("=");
bc=new JButton("C");
p.setLayout(new GridLayout(4,4));
p.add(b[7]);p.add(b[8]);p.add(b[9]);p.add(ba);
p.add(b[4]);p.add(b[5]);p.add(b[6]);p.add(bs);
p.add(b[1]);p.add(b[2]);p.add(b[3]);p.add(bm);
p.add(b[0]);p.add(bd);p.add(be);p.add(bc);
for(int i=0;i<b.length;i++)
b[i].addActionListener(this);
ba.addActionListener(this);
bs.addActionListener(this);
bm.addActionListener(this);
bd.addActionListener(this);
be.addActionListener(this);
bc.addActionListener(this);
f=new JFrame ("简易计算器");
f.setSize(1000,600);
f.add(answer,"North");
f.add(p,"Center");
f.addWindowListener(this);
f.pack();
f.setVisible(true); //表示f这个组建显示为可见
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==bc)
{
s="";
t1=0;
t2=0;
answer.setText("0");
}
else if(e.getSource()==ba)
{
t1=Float.parseFloat(s);
s="";
a=0;
}
else if(e.getSource()==bs)
{
t1=Float.parseFloat(s);
s="";
a=1;
}
else if(e.getSource()==bm)
{
t1=Float.parseFloat(s);
s="";
a=2;
}
else if(e.getSource()==bd)
{
t1=Float.parseFloat(s);
s="";
a=3;
}
else if(e.getSource()==be)
{
t2=Float.parseFloat(s);
if(a==0)
t2=t1+t2;
else if(a==1)
t2=t1-t2;
else if(a==2)
t2=t1*t2;
else if(a==3)
t2=t1/t2;
answer.setText((new Float(t2)).toString());
}
else
{
for(int i=0;i<b.length;i++)
if(e.getSource()==b[i])
{
s=s+b[i].getActionCommand();
answer.setText(s);
}
}
}
public void windowClosing(WindowEvent ev)
{
System.exit(0);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -