java代码写亲戚计算器 java的计算器代码( 四 )


private MyCaculator(){
jpt.setLayout(new BorderLayout());
jpt.add(jtf);
this.add(jpt,BorderLayout.NORTH);
jpb.setLayout(new GridLayout(4,4));
for(int i=0;ijba.length;i++){
jpb.add(jba[i]);
if(i==3||i==7||i==11||i==15||i==14)
jba[i].addActionListener(new setOperate_Act());
else
jba[i].addActionListener(new setLabel_Act());
}
this.add(jpb,BorderLayout.CENTER);
this.setSize(250, 200);
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
3.建立数据计算方法
这里的数据计算方法有6个 , 一个是主方法其他几个是加减乘除的处理方法 , 代码如下:
private void operate(String x){
double x1=Double.valueOf(x);
double y=Double.valueOf(output);
switch(op){
case 0:output=x;break;
case 1:output=String.valueOf(y+x1);break;
case 2:output =String.valueOf(y-x1);break;
case 3:output =String.valueOf(y*x1);break;
case 4:
if(x1!=0) output=String.valueOf(y/x1);
else output="不能为0";
break;
}
}
public String add(String x){
operate(x);
op=add;
return output;
}
public String subtract(String x){
operate(x);
op=sub;
return output;
}
public String multiply(String x){
operate(x);
op=mul;
return output;
}
public String divide(String x){
operate(x);
op=div;
return output;
}
public String Equals(String x){
operate(x);
op=0;
return output;
}
public void opClean(){
op=0;
output ="0";
}
4.事件处理方法
这里的时间处理方法,没有建立一个整体的方法,二是在为了便于处理的方法,将按钮事件分成两个部分,并采用两个子类来实现,这两个类时内部类要写在主类内部的 , 代码如下:
class setOperate_Act implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jba[3]){
jtf.setText(add(jtf.getText()));
ifOp=true;
}
else if(e.getSource()==jba[7]){
jtf.setText(subtract(jtf.getText()));
ifOp=true;
}
else if(e.getSource()==jba[11]){
jtf.setText(multiply(jtf.getText()));
ifOp=true;
}
else if(e.getSource()==jba[15]){
jtf.setText(divide(jtf.getText()));
ifOp=true;
}
else if(e.getSource()==jba[14]){
jtf.setText(Equals(jtf.getText()));
ifOp=true;
}
}
}
class setLabel_Act implements ActionListener{
public void actionPerformed(ActionEvent e) {
Button tempb=(Button)e.getSource();
if(ifOp){
jtf.setText(tempb.getLabel());
ifOp=false;
}else {
jtf.setText(jtf.getText()+tempb.getLabel());
}
}
}
5.建立main方法:
要想实现我们的代码,我们需在main方法中,实例化我们的对象 。
public static void main(String[] args) {
new MyCaculator();
}
用JAVA编写的计算器package main;
import java.awt.Button;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Calculator extends JFrame implements ActionListener {
static Panel pan = new Panel();
static JTextField textField = new JTextField("0");
static Button b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, bp, ba, bs, bm, bd,
be, bc, bt, bf, bh;
private StringBuffer temp = new StringBuffer("");
private String optValue = "https://www.04ip.com/post/0";
private String optType="";

推荐阅读