用JAVA写一个简单的计算器程序有GUI界面(仅实现两个数的加减乘除已经清空)
程序员文章站
2022-05-01 15:53:19
...
用JAVA写一个简单的计算器程序有GUI界面(仅实现两个数的加减乘除已经清空)
前言
很简单易懂的代码
一、java代码
1.代码
package calculate;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class jisuanqi extends JFrame implements ActionListener{
String[] shuzi= {"1","2","3","4","5","6","7","8","9","clear","0","<-"};
String[] fuhao= {"+","-","*","/","="};
JButton[] b=new JButton[12];
JButton[] a=new JButton[5];
JTextField t;
String show="";
String fu;
int n;
int y;
double sum=0;
int shu;
public jisuanqi() {
Container c=getContentPane();
setTitle("计算器");
setSize(300,250);
//布局
//文本框布局
JPanel p=new JPanel(new GridLayout(1,1,1,1));
p.setPreferredSize(new Dimension(300, 30));
//数字
JPanel p1=new JPanel(new GridLayout(4,3,1,1));
p1.setPreferredSize(new Dimension(220, 10));
for (int i=0;i<12;i++) {
b[i]= new JButton(shuzi[i]);
b[i].addActionListener(this);
p1.add(b[i]);
}
//符号
JPanel p2 = new JPanel(new GridLayout(5,1,1,1));
p2.setPreferredSize(new Dimension(60,10));
for (int i=0;i<5;i++) {
a[i]= new JButton(fuhao[i]);
a[i].addActionListener(this);
p2.add(a[i]);
}
//文本框
t=new JTextField("");
p.add(t);
//add
c.add(p, BorderLayout.NORTH);
c.add(p1, BorderLayout.WEST);
c.add(p2, BorderLayout.EAST);
//输入
//总体布局
setVisible(true);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
new jisuanqi();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
String label = e.getActionCommand();
if(label.matches("[1234567890]")) {
show=show+label;
t.setText(show);
shu=Integer.parseInt(show);
}
//加法运算
else if(label=="+") {
y=shu;
show="";
t.setText("");
n=1;
}
//减法
else if(label=="-") {
y=shu;
show="";
t.setText("");
n=2;
}
//乘法
else if(label=="*") {
y=shu;
show="";
t.setText("");
n=3;
}
//除法
else if(label=="/") {
y=shu;
show="";
t.setText("");
if(shu==0){
t.setText("error");
}
else{n=4;}
}
//计算
else if(label=="=") {
show="";
switch (n) {
case 1:
sum=y+shu;
t.setText(""+sum);
break;
case 2:
sum=y-shu;
t.setText(""+sum);
break;
case 3:
sum=y*shu;
t.setText(""+sum);
break;
case 4:
sum=y/shu;
t.setText(""+sum);
break;
}
}
//清空
else if(label=="clear") {
t.setText("");
sum=0;
shu=0;
y=0;
fu="";
show="";
}
}
}
2.结果
总结
我才开始学java算是初学者,只能简单的实现以上功能,有问题欢迎提出来!!