求帮忙设计一个计算器模拟程序。设计要求:(有界面),该程序显示GUI
求帮忙设计一个计算器模拟程序。设计要求:(有界面),该程序显示GUI用户界面,能实现整数的加、减、乘、除四则运算。界面要示:用图形界面实现。……感激不尽...
求帮忙设计一个计算器模拟程序。设计要求:(有界面),该程序显示GUI用户界面,能实现整数的加、减、乘、除四则运算。界面要示:用图形界面实现。……感激不尽
展开
2个回答
2016-06-13
展开全部
/**@version1.322004-05-05@authorCayHorstmann*/importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassCalculator{publicstaticvoidmain(String[]args){CalculatorFrameframe=newCalculatorFrame();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);}}/**Aframewithacalculatorpanel.*/classCalculatorFrameextendsJFrame{publicCalculatorFrame(){setTitle("Calculator");CalculatorPanelpanel=newCalculatorPanel();add(panel);pack();}}/**Apanelwithcalculatorbuttonsandaresultdisplay.*/classCalculatorPanelextendsJPanel{publicCalculatorPanel(){setLayout(newBorderLayout());result=0;lastCommand="=";start=true;//addthedisplaydisplay=newJButton("0");display.setEnabled(false);add(display,BorderLayout.NORTH);ActionListenerinsert=newInsertAction();ActionListenercommand=newCommandAction();//addthebuttonsina4x4gridpanel=newJPanel();panel.setLayout(newGridLayout(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);}/**Addsabuttontothecenterpanel.@paramlabelthebuttonlabel@paramlistenerthebuttonlistener*/privatevoidaddButton(Stringlabel,ActionListenerlistener){JButtonbutton=newJButton(label);button.addActionListener(listener);panel.add(button);}/**Thisactioninsertsthebuttonactionstringtotheendofthedisplaytext.*/privateclassInsertActionimplementsActionListener{publicvoidactionPerformed(ActionEventevent){Stringinput=event.getActionCommand();if(start){display.setText("");start=false;}display.setText(display.getText()+input);}}/**Thisactionexecutesthecommandthatthebuttonactionstringdenotes.*/privateclassCommandActionimplementsActionListener{publicvoidactionPerformed(ActionEventevent){Stringcommand=event.getActionCommand();if(start){if(command.equals("-")){display.setText(command);start=false;}elselastCommand=command;}else{calculate(Double.parseDouble(display.getText()));lastCommand=command;start=true;}}}/**Carriesoutthependingcalculation.@paramxthevaluetobeaccumulatedwiththepriorresult.*/publicvoidcalculate(doublex){if(lastCommand.equals("+"))result+=x;elseif(lastCommand.equals("-"))result-=x;elseif(lastCommand.equals("*"))result*=x;elseif(lastCommand.equals("/"))result/=x;elseif(lastCommand.equals("="))result=x;display.setText(""+result);}privateJButtondisplay;privateJPanelpanel;privatedoubleresult;privateStringlastCommand;privatebooleanstart;}//说明:>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询