这是我在CORE JAVA学到的计算器,挺不错的,发出来给大家看下!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator
{
public static void main(String[] args)
{
CalculatorFrame frame=new CalculatorFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class CalculatorFrame extends JFrame
{
public CalculatorFrame()
{
setTitle("计算器");
pack();
CalculatorPanel p=new CalculatorPanel();
add(p);
}
}
class CalculatorPanel extends JPanel
{
private JButton display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
public CalculatorPanel()
{
setLayout(new BorderLayout());
result=0;
start=true;
lastCommand="=";
display=new JButton("0");
display.setEnabled(false);
add(display,BorderLayout.NORTH);
ActionListener inster=new InsterAction();
ActionListener command=new CommandAction();
panel=new JPanel();
panel.setLayout(new GridLayout(4,4));
add(panel,BorderLayout.CENTER);
addButton("7",inster);
addButton("8",inster);
addButton("9",inster);
addButton("+",command);
addButton("6",inster);
addButton("5",inster);
addButton("4",inster);
addButton("-",command);
addButton("3",inster);
addButton("2",inster);
addButton("1",inster);
addButton("*",command);
addButton("0",inster);
addButton("=",command);
addButton("/",command);
addButton("+/-",command);
}
public void addButton(String label,ActionListener listener)
{
JButton button=new JButton(label);
button.addActionListener(listener);
panel.add(button);
}
private class InsterAction implements ActionListener
{
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
{
public void actionPerformed(ActionEvent e)
{
String command=e.getActionCommand();
if(start)
{
if(command.equals("-"))
{
display.setText(command);
start=false;
}
else
lastCommand=command;
}
else
{
calculator(Double.parseDouble(display.getText()));
lastCommand=command;
start=true;
}
}
}
public void calculator(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;
else if(lastCommand.equals("+/-")) result=-x;
display.setText(""+result);
}
};
[此贴子已经被作者于2006-12-22 0:31:35编辑过]