简单的加减乘除(+-*/ ) 计算器 下拉框 按钮事件

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

public class BaseFrame extends JFrame{

	public BaseFrame (String title)
	{
		setLayout(null);
		setTitle(title);
		setSize(800,300);
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
			System.exit(0);
			}
		});//关闭窗口的匿名类
		setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		
	}
	public void showMe(){
		setVisible(true);
	}
	

	

}


import java.awt.GridLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.*;
public class Calc {
	public static void main(String[] args) {
		JPanel j=new JPanel();
		BaseFrame f=new BaseFrame("hello");
		j.setSize(800,50);
		j.setLayout(new GridLayout(1,5,5,55));
		final JTextField t1=new JTextField();
		final JTextField t2=new JTextField();
		final JTextField t3=new JTextField();
		final JComboBox cb=new JComboBox();
		cb.addItem("+");
		cb.addItem("-");
		cb.addItem("*");
		cb.addItem("/");
		JButton btn =new JButton("=");
		j.add(t1);
		j.add(cb);
		j.add(t2);
		j.add(btn);
		j.add(t3);
		j.setVisible(true);
		f.add(j);
		f.showMe();
//		final String s = cb.getSelectedItem().toString();   说明 不能首先或、获得cb 的值因为  代码的执行从上到下 永远只能获取  到第一个item “+”  而 后面的事件记录无法实现
	    btn.addActionListener(new ActionListener() {	
	    	public void actionPerformed(ActionEvent e) {
	    		
	    	
				if(cb.getSelectedItem().toString().equals("+")){
				int c=0;   	
				int num1 = Integer.parseInt(t1.getText());
				int num2 = Integer.parseInt(t2.getText());
				c=num1+num2;
				String s1=Integer.toString(c);
				t3.setText(s1);
			    }
				else if(cb.getSelectedItem().toString().equals("-")){
					int c=0;   	
					int num1 = Integer.parseInt(t1.getText());
					int num2 = Integer.parseInt(t2.getText());
					c=num1-num2;
					String s1=Integer.toString(c);
					t3.setText(s1);

				}
				else if(cb.getSelectedItem().toString().equals("*")){
					int c=0;   	
					int num1 = Integer.parseInt(t1.getText());
					int num2 = Integer.parseInt(t2.getText());
					c=num1*num2;
					String s1=Integer.toString(c);
					t3.setText(s1);

				}
				else if(cb.getSelectedItem().toString().equals("/")){
					int c=0;   	
					int num1 = Integer.parseInt(t1.getText());
					int num2 = Integer.parseInt(t2.getText());
					c=num1/num2;
					String s1=Integer.toString(c);
					t3.setText(s1);

				}
				else {
					System.out.print("No");
				}
			}
		});
	}
}








posted @ 2016-11-21 20:09  孙中明  阅读(193)  评论(0编辑  收藏  举报