Java计算器源码

来源:互联网 发布:google services.json 编辑:程序博客网 时间:2024/05/01 04:42
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;


public class Calculator extends JPanel 
{
/**

*/
private static final long serialVersionUID = 1L;
private JButton display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;


public Calculator() 
{
setLayout(new BorderLayout());
result = 0;
lastCommand = "=";
start = true;


display = new JButton("0");
display.setEnabled(false);
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 label, ActionListener listener) 
{
   JButton button = new JButton(label);
   button.addActionListener(listener);
   panel.add(button);
}


public class InsertAction implements ActionListener 
{


@Override
public void actionPerformed(ActionEvent e) 
{
String input = e.getActionCommand();
if (start)
{
  display.setText("");
  start = false;
}
display.setText(display.getText() + input);
}


}

public class CommandAction implements ActionListener 
{


@Override
public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();

if (start)
{
if (command.equals("-"))
{
display.setText(command);
start = false;
}
else
{
   lastCommand = command;
   start = true;
}
}
else
{
   caculate(Double.parseDouble(display.getText()));
   lastCommand = command;
   start = true;
}
}

}


public void caculate(double x) 
{
        if (lastCommand.equals("+")) 
        {
        result += x;
        }
        else if (lastCommand.equals("-"))
        {
        result -= x;
        }
        else if (lastCommand.equals("*"))
        {
        result *= x;
        }
        else if (lastCommand.equals("/"))
        {
        result /= x;
        }
        else if (lastCommand.equals("="))
        {
        result = x;
        }
        display.setText("" + result);
}
}































0 0