Java GUI 实现简单计算器

遇到的问题总结一下

  1. 那个setvisiable属性是挺重要的,要么在main函数里设置为true,要么在构造函数最后设置为true,千万不要在构造函数开头设置,那样会出错的
  2. 成员变量的各个属性都在构造函数里设置,什么setlayout,addactionlistener等等
package myTextBook;
import java.awt.*;
import java.awt.event.*;
import java.lang.ref.Cleaner.Cleanable;

import javax.swing.*;


public class Calculator extends JFrame {
	JPanel northPanel = new JPanel();JPanel centerPanel = new JPanel();
	JTextField jTextField= new JTextField(20);
	JButton cleaButton = new JButton("<");
	JButton [] buttons = new JButton [16];
	double num1,num2,result,flag=0;
	String op = new String("");
	
	public Calculator(){
		Container con = this.getContentPane();
		con.setLayout(new BorderLayout(5, 5));
		
		this.setSize(300, 400);
		this.setTitle("计算器");
		this.setResizable(false);
		this.setLocation(200, 200);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	
		northPanel.setLayout(new FlowLayout(1));centerPanel.setLayout(new GridLayout(4,4,20,20));
		jTextField.setText("");
		northPanel.add(jTextField);northPanel.add(cleaButton);
		
		String [] titles = {
				"1","2","3","+","4","5","6","-",
				"7","8","9","*","0",".","=","/",
		};
		cleaButton.addActionListener(new myListener());//注册监听器
		for( int i=0; i<16; i++ ) {
			buttons[i]=new JButton(titles[i]);
			buttons[i].addActionListener(new myListener());//注册监听器
			centerPanel.add(buttons[i]);
		}
		con.add(northPanel,BorderLayout.NORTH);
		con.add(centerPanel,BorderLayout.CENTER);
	}
	class myListener implements ActionListener{
		public void actionPerformed(ActionEvent e) {
			String cmd = e.getActionCommand();
			char key = cmd.charAt(0);
			switch(key) {
			case '0':case '1':case '2':case '3':case '4':case '5':case '6':case '7':case '8':case '9':{
				if(flag==0) jTextField.setText(jTextField.getText()+key);
				else if(flag==1) {
					jTextField.setText("");flag=0;
					jTextField.setText(jTextField.getText()+key);
				}
			}break;
			case '<':{
				num1=num2=0;op="";
				jTextField.setText("");
			}break;
			case '+':case '-':case '*':case '/':{
				if(!jTextField.getText().equals("")) {
					num1=Double.parseDouble(jTextField.getText());
				}
				op=Character.toString(key);flag=1;
			}break;
			case '=':{
				if(!jTextField.getText().equals("")) {
					num2=Double.parseDouble(jTextField.getText());
					if(op.equals("+")) jTextField.setText(Double.toString(num1+num2));
					else if(op.equals("-")) jTextField.setText(Double.toString(num1-num2));
					else if(op.equals("*")) jTextField.setText(Double.toString(num1*num2));
					else if(op.equals("/")&&num2!=0) jTextField.setText(Double.toString(num1/num2));
					op="";
				}
			}
			}
		}
	}
	public static void main(String[] args) {
		Calculator calculator =new Calculator();
		calculator.setVisible(true);
	}
}

你可能感兴趣的:(Java)