Java实现常规的计算器(网格布局)

      计算器的布局比较整齐,利用网格布局排列计算器按钮是一种比较理想的方式,实现的java程序如下:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/**
 * 
 * @author IWong
 *
 */
public class Calculator {
	public static void main(String[] args) {
		EventQueue.invokeLater(() -> {
	         CalculatorFrame frame = new CalculatorFrame();
	         frame.setTitle("计算器");
	         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	         frame.setVisible(true);
	      });
	}
}

class CalculatorFrame extends JFrame{
	public CalculatorFrame() {
		add(new CalculatorPanel());
		pack();
	}
	
}

class CalculatorPanel extends JPanel{
	private JPanel panel;
	private JTextField display;
	private double result;
	private String lastcommand;
	private boolean start=true;
	public CalculatorPanel() {
		setLayout(new BorderLayout());
		display=new JTextField();
		display.setHorizontalAlignment(JTextField.RIGHT);
		result=0;
		display.setText(""+result);
		add(display,BorderLayout.NORTH);
		ActionListener insert=new InsertAction();
		ActionListener command=new CommandAction();
		panel=new JPanel();
		panel.setLayout(new GridLayout(4,4));
		addButton("7",insert);
		addButton("8",insert);
		addButton("9",insert);
		addButton("/",command);
		addButton("4",insert);
		addButton("5",insert);
		addButton("6",insert);
		addButton("*",command);
		addButton("1",insert);
		addButton("2",insert);
		addButton("3",insert);
		addButton("+",command);
		addButton("0",insert);
		addButton(".",insert);
		addButton("=",command);
		addButton("+",command);
		add(panel,BorderLayout.CENTER);	
	}
	
	private void addButton(String s, ActionListener listener) {
		JButton button=new JButton(s);
		button.addActionListener(listener);
		panel.add(button);
	}
	
	private class InsertAction implements ActionListener{
		public void actionPerformed(ActionEvent event) {
			String input=event.getActionCommand();
			if(start){
				display.setText("");
				start=false;
			}
			display.setText(display.getText()+input);
		}
	}
	private class CommandAction implements ActionListener{
		public void actionPerformed(ActionEvent event) {
			String command=event.getActionCommand();
			if(command.equals("=")){			
				if(lastcommand.equals("+")) result+=Double.parseDouble(display.getText());			
				if(lastcommand.equals("-")) result-=Double.parseDouble(display.getText());			
				if(lastcommand.equals("*")) result*=Double.parseDouble(display.getText());			
				if(lastcommand.equals("/")) result/=Double.parseDouble(display.getText());
				display.setText(""+result);
				start=true;
			}else{
				result=Double.parseDouble(display.getText());			
				lastcommand=command;
				start=true;
			}
		}
	}
	
}

你可能感兴趣的:(Swing,Java,事件处理)