用java编写简易计算器程序
1个回答
展开全部
//布局没有调整,需要你自己去调整
代码如下:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JieMian extends JFrame implements ActionListener{
JTextField c1;
JTextField c2;
JLabel c;
JLabel equal=new JLabel("=");
JLabel result;
JLabel choose=new JLabel("请选择");
JButton add=new JButton("+");
JButton sub=new JButton("-");
JButton mul=new JButton("×");
JButton div=new JButton("÷");
JButton cal=new JButton("计算");
JButton clear=new JButton("清除");
public JieMian(){
setLayout(new FlowLayout());
c1=new JTextField(5);
c2=new JTextField(5);
c=new JLabel("+");
result=new JLabel("");
add(c1);
add(c);
add(c2);
add(equal);
add(result);
add(choose);
add(add);
add(sub);
add(mul);
add(div);
add(cal);
add(clear);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
cal.addActionListener(this);
clear.addActionListener(this);
setVisible(true);
pack();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==add){
c.setText("+");
}else if(e.getSource()==sub){
c.setText("-");
}else if(e.getSource()==mul){
c.setText("×");
}else if(e.getSource()==div){
c.setText("÷");
}else if(e.getSource()==cal){
double cc1,cc2;
try{
cc1=Double.parseDouble(c1.getText());
}catch(Exception ex){
cc1=0;
}try{
cc2=Double.parseDouble(c2.getText());
}catch(Exception ex){
cc2=0;
}
if(c.getText()=="+"){
result.setText(String.valueOf(cc1+cc2));
}else if(c.getText()=="-"){
result.setText(String.valueOf(cc1-cc2));
}else if(c.getText()=="×"){
result.setText(String.valueOf(cc1*cc2));
}else if(c.getText()=="÷"){
if(cc2!=0){
result.setText(String.valueOf(cc1/cc2));
}else{
result.setText("NAN");
}
}
}else if(e.getSource()==clear){
c1.setText("");
c2.setText("");
result.setText("");
}
}
public static void main(String args[]){
JieMian jiemian=new JieMian();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询