java 简单的计算器程序
实现实例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class calculator
{
public static void main(string[] args)
{
eventqueue.invokelater(new runnable()
{
public void run()
{
calculatorframe frame = new calculatorframe();
frame.setdefaultcloseoperation(jframe.exit_on_close);
frame.setvisible(true);
}
});
}
}
/**
* a frame with a calculator panel.
*/
class calculatorframe extends jframe
{
public calculatorframe()
{
settitle("calculator");
calculatorpanel panel=new calculatorpanel();
add(panel);
pack();
}
}
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;
lastcommand="=";
start=true;
// add the display
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);
}
/**
* this action inserts the button action string to the end of the display text.
*/
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);
}
}
/**
* this action executes the command that the button action string denotes.
*/
private class commandaction implements actionlistener
{
public void actionperformed(actionevent event)
{
string command=event.getactioncommand();
if(start)
{
if (command.equals("-"))
{
display.settext(command);
start = false;
}
else lastcommand = command;
}else {
calculate(double.parsedouble(display.gettext()));
lastcommand=command;
start=true;
}
}
}
/**
* carries out the pending calculation.
* @param x the value to be accumulated with the prior result.
*/
public void calculate(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);
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
希望与广大网友互动??
点此进行留言吧!