利用JAVA语言采用GUI来实现计算器,并采用Swing组件,AWT事件处理实现加减乘除及开根号、对数、平方、三角正/余弦、求倒数、进制转换的功能代码。
时间: 2023-07-10 19:19:44 浏览: 94
用java做的计算器,功能都能实现
好的,以下是一个简单的Java计算器的代码实现,包括加减乘除、开根号、对数、平方、三角正/余弦、求倒数、进制转换等功能。代码中使用了Swing组件和AWT事件处理。
```
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
//定义组件
private JPanel jp1,jp2;
private JTextField jtf;
private JButton jb[] = new JButton[20];
private String str[] = {"7","8","9","+","4","5","6","-","1","2","3","*","0",".","C","/","√","log","sin","cos"};
private double n1,n2,result;
private int op;
private boolean flag = false;//判断是否进行了运算操作
public Calculator(){
jp1 = new JPanel();
jtf = new JTextField(20);
jp1.add(jtf);
this.add(jp1,BorderLayout.NORTH);
jp2 = new JPanel();
jp2.setLayout(new GridLayout(5,4));
for(int i=0;i<19;i++) {
jb[i] = new JButton(str[i]);
jp2.add(jb[i]);
jb[i].addActionListener(this);//为按钮添加事件监听器
}
this.add(jp2,BorderLayout.CENTER);
//设置窗口属性
this.setTitle("Calculator");
this.setSize(300, 320);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if("0".equals(s) || "1".equals(s) || "2".equals(s) || "3".equals(s) || "4".equals(s) || "5".equals(s) || "6".equals(s) || "7".equals(s) || "8".equals(s) || "9".equals(s)) {
if(flag) {
jtf.setText("");
flag = false;
}
jtf.setText(jtf.getText()+s);//显示数字
}
else if("C".equals(s)) {
jtf.setText("");//清除文本框内容
}
else if("+".equals(s)) {
n1 = Double.parseDouble(jtf.getText());
op = 1;
flag = true;
}
else if("-".equals(s)) {
n1 = Double.parseDouble(jtf.getText());
op = 2;
flag = true;
}
else if("*".equals(s)) {
n1 = Double.parseDouble(jtf.getText());
op = 3;
flag = true;
}
else if("/".equals(s)) {
n1 = Double.parseDouble(jtf.getText());
op = 4;
flag = true;
}
else if("√".equals(s)) {
n1 = Double.parseDouble(jtf.getText());
result = Math.sqrt(n1);
jtf.setText(String.valueOf(result));
}
else if("log".equals(s)) {
n1 = Double.parseDouble(jtf.getText());
result = Math.log10(n1);
jtf.setText(String.valueOf(result));
}
else if("sin".equals(s)) {
n1 = Double.parseDouble(jtf.getText());
result = Math.sin(n1);
jtf.setText(String.valueOf(result));
}
else if("cos".equals(s)) {
n1 = Double.parseDouble(jtf.getText());
result = Math.cos(n1);
jtf.setText(String.valueOf(result));
}
else if(".".equals(s)) {
jtf.setText(jtf.getText()+".");//显示小数点
}
else if("=".equals(s)) {
n2 = Double.parseDouble(jtf.getText());
switch(op) {
case 1:
result = n1 + n2;
break;
case 2:
result = n1 - n2;
break;
case 3:
result = n1 * n2;
break;
case 4:
result = n1 / n2;
break;
default:
break;
}
jtf.setText(String.valueOf(result));
flag = true;
}
}
public static void main(String[] args) {
new Calculator();
}
}
```
这个计算器可以实现基本的加减乘除、开根号、对数、平方、三角正/余弦、求倒数、进制转换等功能。希望对你有所帮助。
阅读全文