Java版本JFrame,計算器和單位換算的實現

  1. 創建計算類
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    /**
     * 一個計算器,與Windows附件自帶計算器的標準版功能、界面相仿。 但還不支持鍵盤操作。
     */
    public class Calculator {
    	//計算器按鈕顯示文本
    	String[] btntext= {"MC", "MR", "MS", "M+", "%", "√", "x^2", "1/x", "CE", "C", "Bak", "÷",
    			"7", "8", "9", "x", "4", "5", "6", "-", "1", "2", "3", "+",
    			"+/-", "0", ".", "=",};
    	//放置結果文本域
    	JTextField resultText=new JTextField();
    	// 標誌用戶按的是否是整個表達式的第一個數字,或者是運算符後的第一個數字
        private boolean firstDigit = true;
        // 計算的中間結果。
        private double resultNum = 0.0;
        // 當前運算的運算符
        private String operator = "=";
        // 操作是否合法
        private boolean operateValidFlag = true;
    	/**
    	 * 獲取計算器面板
    	 * @return 計算器面板
    	 */
    	public JPanel getCalculator() {
    		JPanel jp=new JPanel();
    		jp.setLayout(new BorderLayout());//設置佈局
    		
    		resultText.setText("0");
    		jp.add(resultText, BorderLayout.NORTH);
    		//放置所有操作按鈕
    		JPanel opt=new JPanel();
    		opt.setLayout(new GridLayout(7, 4));
    		for(String str : btntext) {
    			JButton btn=new JButton(str);
    			btn.addActionListener(new ActionListener() {
    				@Override
    				public void actionPerformed(ActionEvent e) {
    					// 獲取事件源的標籤
    			        String label = e.getActionCommand();
    			        if (label.equals("Bak")) {
    			            // 用戶按了"Backspace"鍵
    			            handleBackspace();
    			        } else if (label.equals("CE")) {
    			            // 用戶按了"CE"鍵
    			            resultText.setText("0");
    			        } else if (label.equals("C")) {
    			            // 用戶按了"C"鍵
    			            handleC();
    			        } else if ("0123456789.".indexOf(label) >= 0) {
    			            // 用戶按了數字鍵或者小數點鍵
    			            handleNumber(label);
    			            // handlezero(zero);
    			        } else {
    			            // 用戶按了運算符鍵
    			            handleOperator(label);
    			        }
    				}
    			});
    			opt.add(btn);
    		}
    		jp.add(opt, BorderLayout.CENTER);
    		return jp;
    	}
     
        /**
         * 處理Backspace鍵被按下的事件
         */
        private void handleBackspace() {
            String text = resultText.getText();
            int i = text.length();
            if (i > 0) {
                // 退格,將文本最後一個字符去掉
                text = text.substring(0, i - 1);
                if (text.length() == 0) {
                    // 如果文本沒有了內容,則初始化計算器的各種值
                    resultText.setText("0");
                    firstDigit = true;
                    operator = "=";
                } else {
                    // 顯示新的文本
                    resultText.setText(text);
                }
            }
        }
     
        /**
         * 處理數字鍵被按下的事件
         *
         * @param key
         */
        private void handleNumber(String key) {
            if (firstDigit) {
                // 輸入的第一個數字
                resultText.setText(key);
            } else if ((key.equals(".")) && (resultText.getText().indexOf(".") < 0)) {
                // 輸入的是小數點,並且之前沒有小數點,則將小數點附在結果文本框的後面
                resultText.setText(resultText.getText() + ".");
            } else if (!key.equals(".")) {
                // 如果輸入的不是小數點,則將數字附在結果文本框的後面
                resultText.setText(resultText.getText() + key);
            }
            // 以後輸入的肯定不是第一個數字了
            firstDigit = false;
        }
     
        /**
         * 處理C鍵被按下的事件
         */
        private void handleC() {
            // 初始化計算器的各種值
            resultText.setText("0");
            firstDigit = true;
            operator = "=";
        }
     
        /**
         * 處理運算符鍵被按下的事件
         *
         * @param key
         */
        private void handleOperator(String key) {
            if (operator.equals("÷")) {
                // 除法運算
                // 如果當前結果文本框中的值等於0
                if (getNumberFromText() == 0.0) {
                    // 操作不合法
                    operateValidFlag = false;
                    resultText.setText("除數不能爲零");
                } else {
                    resultNum /= getNumberFromText();
                }
            } else if (operator.equals("1/x")) {
                // 倒數運算
                if (resultNum == 0.0) {
                    // 操作不合法
                    operateValidFlag = false;
                    resultText.setText("零沒有倒數");
                } else {
                    resultNum = 1 / resultNum;
                }
            } else if (operator.equals("+")) {
                // 加法運算
                resultNum += getNumberFromText();
            } else if (operator.equals("-")) {
                // 減法運算
                resultNum -= getNumberFromText();
            } else if (operator.equals("x")) {
                // 乘法運算
                resultNum *= getNumberFromText();
            }else if (operator.equals("x^2")) {
            	resultNum *= resultNum;
            } else if (operator.equals("√")) {
                // 平方根運算
                resultNum = Math.sqrt(resultNum);
            } else if (operator.equals("%")) {
                // 百分號運算,除以100
                resultNum = resultNum / 100;
            } else if (operator.equals("+/-")) {
                // 正數負數運算
                resultNum = resultNum * (-1);
            } else if (operator.equals("=")) {
                // 賦值運算
                resultNum = getNumberFromText();
            }
            if (operateValidFlag) {
                // 雙精度浮點數的運算
                long t1;
                double t2;
                t1 = (long) resultNum;
                t2 = resultNum - t1;
                if (t2 == 0) {
                    resultText.setText(String.valueOf(t1));
                } else {
                    resultText.setText(String.valueOf(resultNum));
                }
            }
            // 運算符等於用戶按的按鈕
            operator = key;
            firstDigit = true;
            operateValidFlag = true;
        }
     
        /**
         * 從結果文本框中獲取數字
         *
         * @return
         */
        private double getNumberFromText() {
            double result = 0;
            try {
                result = Double.valueOf(resultText.getText()).doubleValue();
            } catch (NumberFormatException e) {
            }
            return result;
        }
    }

     

  2. 創建單位換算
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.regex.Pattern;
    
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JToolBar;
    
    public class Convert {
    
    	private static Map<String, String[][]> toolbarmap = new HashMap<String, String[][]>();
    	private static String[][] conrate=null;
    	private static JLabel jl=new JLabel();//顯示標題
    	private static JComboBox<String> convert=new JComboBox<String>();
    	private static JComboBox<String> converted=new JComboBox<String>();
    	private static JTextField tconvert=new JTextField();
    	private static JTextField tconverted=new JTextField();
    
    	static {
    		tconverted.setEditable(false);
    		/*
    		 * 		釐米		分米		米		千米(輸入項)
    		 * 釐米	1		10		100		100000
    		 * 分米	0.1		1		10		10000
    		 * 米	0.01	0.1		1		1000
    		 * 千米	0.00001	0.0001	0.001	1
    		 */
    		String[][] len = new String[4][5];
    		len[0] = new String[5];
    		len[1] = new String[5];
    		len[2] = new String[5];
    		len[3] = new String[5];
    		len[0][0]="釐米";
    		len[1][0]="分米";
    		len[2][0]="米";
    		len[3][0]="千米";
    		len[0][1]="1";
    		len[1][1]="10";
    		len[2][1]="100";
    		len[3][1]="100000";
    		len[0][2]="0.1";
    		len[1][2]="1";
    		len[2][2]="10";
    		len[3][2]="10000";
    		len[0][3]="0.01";
    		len[1][3]="0.1";
    		len[2][3]="1";
    		len[3][3]="1000";
    		len[0][4]="0.00001";
    		len[1][4]="0.0001";
    		len[2][4]="0.001";
    		len[3][4]="1";
    		toolbarmap.put("長度(L)", len);
    		/*
    		 * 			平方釐米		平方分米		平方米(輸入項)
    		 * 平方釐米	1			100			10000	
    		 * 平方分米	0.01		1			100	
    		 * 平方米	0.0001		0.01		1	
    		 */
    		String[][] area = new String[3][4];
    		area[0] = new String[4];
    		area[1] = new String[4];
    		area[2] = new String[4];
    		area[0][0]="平方釐米";
    		area[1][0]="平方分米";
    		area[2][0]="平方米";
    		area[0][1]="1";
    		area[1][1]="100";
    		area[2][1]="10000";
    		area[0][2]="0.01";
    		area[1][2]="1";
    		area[2][2]="100";
    		area[0][3]="0.0001";
    		area[1][3]="0.01";
    		area[2][3]="1";
    		toolbarmap.put("面積(S)", area);
    		/*
    		 * 			立方厘米		立方分米		立方米(輸入項)
    		 * 立方厘米	1			1000		100000	
    		 * 立方分米	0.001		1			1000	
    		 * 立方米	0.000001	0.001		1	
    		 */
    		String[][] vol = new String[3][4];
    		vol[0] = new String[4];
    		vol[1] = new String[4];
    		vol[2] = new String[4];
    		vol[0][0]="立方厘米";
    		vol[1][0]="立方分米";
    		vol[2][0]="立方米";
    		vol[0][1]="1";
    		vol[1][1]="1000";
    		vol[2][1]="1000000";
    		vol[0][2]="0.001";
    		vol[1][2]="1";
    		vol[2][2]="1000";
    		vol[0][3]="0.000001";
    		vol[1][3]="0.001";
    		vol[2][3]="1";
    		toolbarmap.put("體積(V)", vol);
    		/*
    		 * 			攝氏度		華氏度		開爾文(輸入項)
    		 * 攝氏度	1			-17.2222	-272.15	
    		 * 華氏度	33.8		1			-475.87	
    		 * 開爾文	274.15		255.9278	1	
    		 */
    		String[][] temperature = new String[3][4];
    		temperature[0] = new String[4];
    		temperature[1] = new String[4];
    		temperature[2] = new String[4];
    		temperature[0][0]="攝氏度";
    		temperature[1][0]="華氏度";
    		temperature[2][0]="開爾文";
    		temperature[0][1]="1";
    		temperature[1][1]="-17.2222";
    		temperature[2][1]="-272.15";
    		temperature[0][2]="33.8";
    		temperature[1][2]="1";
    		temperature[2][2]="-475.87";
    		temperature[0][3]="274.15";
    		temperature[1][3]="255.9278";
    		temperature[2][3]="1";
    		toolbarmap.put("溫度(K)", temperature);
    		/*
    		 * 			焦耳			千焦耳		卡路里(輸入項)
    		 * 焦耳		1			1000		4.184	
    		 * 千焦耳	0.001		1			0.004184	
    		 * 卡路里	0.239006	239.0057	1	
    		 */
    		String[][] heat = new String[3][4];
    		heat[0] = new String[4];
    		heat[1] = new String[4];
    		heat[2] = new String[4];
    		heat[0][0]="焦耳";
    		heat[1][0]="千焦耳";
    		heat[2][0]="卡路里";
    		heat[0][1]="1";
    		heat[1][1]="1000";
    		heat[2][1]="4.184";
    		heat[0][2]="0.001";
    		heat[1][2]="1";
    		heat[2][2]="0.004184";
    		heat[0][3]="0.239006";
    		heat[1][3]="239.0057";
    		heat[2][3]="1";
    		toolbarmap.put("能量(Q)", heat);
    		/*
    		 * 			度			弧度			百分度(輸入項)
    		 * 度		1			57.29578	0.9	
    		 * 弧度		0.017453	1			0.015708	
    		 * 百分度	1.111111	63.66198	1	
    		 */
    		String[][] ang = new String[3][4];
    		ang[0] = new String[4];
    		ang[1] = new String[4];
    		ang[2] = new String[4];
    		ang[0][0]="度";
    		ang[1][0]="弧度";
    		ang[2][0]="百分度";
    		ang[0][1]="1";
    		ang[1][1]="57.29578";
    		ang[2][1]="0.9";
    		ang[0][2]="0.017453";
    		ang[1][2]="1";
    		ang[2][2]="0.015708";
    		ang[0][3]="1.111111";
    		ang[1][3]="63.66198";
    		ang[2][3]="1";
    		toolbarmap.put("角度(A)", ang);
    		/*
    		 * 			釐米/秒		米/秒		公里/小時(輸入項)
    		 * 釐米/秒	1			100			27.7777777
    		 * 米/秒		0.01		1			0.2777777	
    		 * 公里/小時	0.036		3.6			1	
    		 */
    		String[][] career = new String[3][4];
    		career[0] = new String[4];
    		career[1] = new String[4];
    		career[2] = new String[4];
    		career[0][0]="釐米/秒";
    		career[1][0]="米/秒";
    		career[2][0]="公里/小時";
    		career[0][1]="1";
    		career[1][1]="100";
    		career[2][1]="27.7777777";
    		career[0][2]="0.01";
    		career[1][2]="1";
    		career[2][2]="0.2777777";
    		career[0][3]="0.036";
    		career[1][3]="3.6";
    		career[2][3]="1";
    		toolbarmap.put("速度(R)", career);
    		/*
    		 * 		巴		帕		千帕(輸入項)
    		 * 巴	1		0.00001	0.01
    		 * 帕	100000	1		1000
    		 * 千帕	100		0.001	1
    		 */
    		String[][] press = new String[3][4];
    		press[0] = new String[4];
    		press[1] = new String[4];
    		press[2] = new String[4];
    		press[0][0]="巴";
    		press[1][0]="帕";
    		press[2][0]="千帕";
    		press[0][1]="1";
    		press[1][1]="0.00001";
    		press[2][1]="0.01";
    		press[0][2]="100000";
    		press[1][2]="1";
    		press[2][2]="1000";
    		press[0][3]="100";
    		press[1][3]="0.001";
    		press[2][3]="1";
    		toolbarmap.put("壓力(P)", press);
    		/*
    		 * 		克			千克			噸			磅(輸入項)
    		 * 克	1			1000		1000000		453.5924
    		 * 千克	0.001		1			1000		0.453592
    		 * 噸	0.000001	0.001		1			0.000454
    		 * 磅	0.002205	2.204623	2204.623	1
    		 */
    		String[][] qua = new String[4][5];
    		qua[0] = new String[5];
    		qua[1] = new String[5];
    		qua[2] = new String[5];
    		qua[3] = new String[5];
    		qua[0][0]="克";
    		qua[1][0]="千克";
    		qua[2][0]="噸";
    		qua[3][0]="磅";
    		qua[0][1]="1";
    		qua[1][1]="1000";
    		qua[2][1]="1000000";
    		qua[3][1]="453.5924";
    		qua[0][2]="0.001";
    		qua[1][2]="1";
    		qua[2][2]="1000";
    		qua[3][2]="0.453592";
    		qua[0][3]="0.000001";
    		qua[1][3]="0.001";
    		qua[2][3]="1";
    		qua[3][3]="0.000454";
    		qua[0][4]="0.002205";
    		qua[1][4]="2.204623";
    		qua[2][4]="2204.623";
    		qua[3][4]="1";
    		toolbarmap.put("重量(M)", qua);
    		/*
    		 * 		瓦特			千瓦			馬力(輸入項)
    		 * 瓦特	1			1000		745.6999
    		 * 千瓦	0.001		1			0.7457
    		 * 馬力	0.001341022	1.341022	1
    		 */
    		String[][] ele = new String[3][4];
    		ele[0] = new String[4];
    		ele[1] = new String[4];
    		ele[2] = new String[4];
    		ele[0][0]="瓦特";
    		ele[1][0]="千瓦";
    		ele[2][0]="馬力";
    		ele[0][1]="1";
    		ele[1][1]="1000";
    		ele[2][1]="745.6999";
    		ele[0][2]="0.001";
    		ele[1][2]="1";
    		ele[2][2]="0.7457";
    		ele[0][3]="0.001341022";
    		ele[1][3]="1.341022";
    		ele[2][3]="1";
    		toolbarmap.put("功率(W)", ele);
    		/*
    		 * 			元			美元			歐元(輸入項)
    		 * 元		1			6.91		7.81
    		 * 美元		0.14		1			1.13
    		 * 歐元		0.13		0.88		1
    		 */
    		String[][] dol = new String[3][4];
    		dol[0] = new String[4];
    		dol[1] = new String[4];
    		dol[2] = new String[4];
    		dol[0][0]="元";
    		dol[1][0]="美元";
    		dol[2][0]="歐元";
    		dol[0][1]="1";
    		dol[1][1]="6.91";
    		dol[2][1]="7.81";
    		dol[0][2]="0.14";
    		dol[1][2]="1";
    		dol[2][2]="1.13";
    		dol[0][3]="0.13";
    		dol[1][3]="0.88";
    		dol[2][3]="1";
    		toolbarmap.put("貨幣(¥)", dol);
    	}
    	/**
    	 * 獲取計算器面板
    	 * 
    	 * @return 計算器面板
    	 */
    	public JPanel getConvert() {
    		JPanel jp = new JPanel();
    		jp.setLayout(new BorderLayout());// 設置佈局
    		JToolBar jtb = new JToolBar();
    		jtb.setFloatable(true);
    		//jtb.setOrientation(SwingConstants.HORIZONTAL);
    		for (String str : toolbarmap.keySet()) {
    			JButton jb = new JButton(str);
    			jb.addActionListener(new ActionListener() {
    				@Override
    				public void actionPerformed(ActionEvent e) {
    					setopcentext(str);
    				}
    			});
    			jtb.add(jb);
    		}
    		jp.add(jtb, BorderLayout.NORTH);
    		//添加中央顯示面板
    		setopcentext("長度(L)");
    		JPanel center=new JPanel();
    		center.setLayout(new GridLayout(6, 1));
    		center.add(jl);
    		center.add(convert);
    		center.add(tconvert);
    		center.add(converted);
    		center.add(tconverted);
    		//單位換算提交按鈕
    		JButton sure=new JButton("確定");
    		//添加點擊事件監聽事件
    		sure.addActionListener(new ActionListener() {
    			@Override
    			public void actionPerformed(ActionEvent arg0) {
    				double rate=Double.parseDouble(conrate[convert.getSelectedIndex()][converted.getSelectedIndex()+1]);
    				String in=tconvert.getText();
    				String pattern = "^(\\-|\\+)?\\d+(\\.\\d+)?$";
    				double i=0.0;
    				if(Pattern.matches(pattern, in)) {
    					i=Double.parseDouble(in);
    					tconverted.setText(Double.toString(rate*i));
    				}else tconverted.setText("請輸入正確的數字格式");
    			}
    		});
    		center.add(sure, BorderLayout.SOUTH);
    		jp.add(center);
    		return jp;
    	}
    	/**
    	 * 設置操作項文本,下拉選項等
    	 * @param type 操作類型  長度等
    	 */
    	private void setopcentext(String type) {
    		convert.removeAllItems();
    		converted.removeAllItems();
    		conrate=toolbarmap.get(type);
    		jl.setText(type);
    		for(String[] s : conrate) {
    			convert.addItem(s[0]);
    			converted.addItem(s[0]);
    		};
    	}
    }

     

  3. 啓動類
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class MyCalculator extends JFrame {
    	private static final long serialVersionUID = 1L;
    
    	public MyCalculator() {
    		super("計算器");
    		JFrame jframe=this;
    		this.setLayout(new BorderLayout());
    		//添加計算器面板
    		JPanel pcal=new Calculator().getCalculator();
    		JPanel pcon=new Convert().getConvert();
    		this.getContentPane().add(pcal, BorderLayout.CENTER);
    		//this.getContentPane().add(pcon, BorderLayout.CENTER);
    		//計算器,單位轉換操作按鈕
    		JPanel btn=new JPanel();
    		btn.setLayout(new GridLayout(1, 2));
    		JButton cal=new JButton("計算器");
    		cal.addActionListener(new ActionListener() {
    			@Override
    			public void actionPerformed(ActionEvent arg0) {
    				pcon.setVisible(false);
    				pcal.setVisible(true);
    				jframe.getContentPane().add(pcal, BorderLayout.CENTER);
    			}
    		});
    		JButton con=new JButton("單位轉換");
    		con.addActionListener(new ActionListener() {
    			@Override
    			public void actionPerformed(ActionEvent arg0) {
    				pcon.setVisible(true);
    				pcal.setVisible(false);
    				jframe.getContentPane().add(pcon, BorderLayout.CENTER);
    			}
    		});
    		btn.add(cal);
    		btn.add(con);
    		this.add(btn, BorderLayout.SOUTH);
    		//設置窗體屬性
    		this.setVisible(true);
    		this.setBounds(100, 100, 634, 300);//設置窗體的位置和大小
    	}
    	public static void main(String[] args) {
    		new MyCalculator();
    	}
    }

    好了,完成了,歡迎加羣QQ討論 517413713

發佈了8 篇原創文章 · 獲贊 13 · 訪問量 4598
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章