日期:2014-05-20 浏览次数:20729 次
public class Main
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
CalculatorFrame test = new CalculatorFrame();
}
}
/**
* 计算器界面
* @author Administrator
*
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CalculatorFrame extends JFrame
{
public CalculatorFrame()
{
setTitle("书上的计算器");
CalulatorPanel panel = new CalulatorPanel();
add( panel );
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible( true );
pack();
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CalulatorPanel extends JPanel
{
public CalulatorPanel()
{
this.setLayout(new BorderLayout() );
result = 0;
lastCommand = "=";
start = true;
//添加显示
display = new JButton("0");
display.setEnabled(false);
add( display, BorderLayout.NORTH);
InsertAction insert = new InsertAction();
CommandAction 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 listrner )
{
JButton button = new JButton( label );
button.addActionListener(listrner);
panel.add( button );
}
private class InsertAction implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
String input = e.getActionCommand();
if( start )
{
display.setText("");
start = false;
}
display.setText(display.getText() + input );
//System.out.println( start );
}
}
private class CommandAction implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
String command = e.getActionCommand();
if( start )
{
if( command.equals("-"))
{
display.setText( command );
start = false;
}
else
{
lastCommand = command;
}
System.out.println( start );
}
else
{
calcucate( Double.parseDouble(display.getText()));//这里有问题
lastCommand = command;
start = true;
//System.out.println( start );
}
}
}
//计算
public void calcucate( 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 );
//System.out.println(result + " " + x );
}
private JButton display;//显示结果
private JPanel panel;//数字和符号
private double result;//计算结果
private String lastCommand;
private boolean start;
}