m0_59221003 2021-06-12 01:56 采纳率: 100%
浏览 35
已采纳

简易计算器怎么写用JAVA

 

  • 写回答

3条回答 默认 最新

  • 关注
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    
    public class 简单计算器  extends JFrame implements ActionListener{
    	JTextField txtNum1,txtNum2,txtNum3;
    	JComboBox<String> cbOpr;
    	String opr[] = {"+","-","*","/"};
    	JButton btnCalc;
    	public 简单计算器() {
    		super("简单计算器");
    		
    		txtNum1 = new JTextField(6);
    		cbOpr = new JComboBox<String>(opr);
    		txtNum2 = new JTextField(6);
    		txtNum3 = new JTextField(6);
    		btnCalc = new JButton("=");
    		JPanel northPane = new JPanel(new FlowLayout());
    		northPane.add(txtNum1);
    		northPane.add(cbOpr);
    		northPane.add(txtNum2);
    		northPane.add(btnCalc);
    		northPane.add(txtNum3);
    		txtNum3.setEnabled(false);
    		add(northPane);
    		btnCalc.addActionListener(this);
    		this.pack();
    		setVisible(true);
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setLocationRelativeTo(null);
    		
    	}
    	@Override
    	public void actionPerformed(ActionEvent e) {
    		
    		try {
    			double num1 = Double.parseDouble(txtNum1.getText());
    			double num2 = Double.parseDouble(txtNum2.getText());
    			int index = cbOpr.getSelectedIndex();
    			switch(index) {
    			case 0:
    				txtNum3.setText((num1+num2)+"");
    				break;
    			case 1:
    				txtNum3.setText((num1-num2)+"");
    				break;
    			case 2:
    				txtNum3.setText((num1*num2)+"");
    				break;
    			case 3:
    				txtNum3.setText((num1/num2)+"");
    				break;
    			}
    		}catch(Exception ex){
    			System.out.println("出错了"+ex.getMessage());
    		}
    	}
    	public static void main(String[] args) {
    		new 简单计算器();
    	}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?