public static void main(String[] args) { new MyCalculator().go(); }
/** *采用成員內部類方式,實現監聽器接口,方便訪問主類內類內部成員。 *此類負責數字按鈕Action事件監聽和處理 */ class NumberListener implements ActionListener{ public void actionPerformed(ActionEvent e){ if (!append) { tf.setText(""); append=true; } String s=tf.getText(); s+=e.getActionCommand(); tf.setText(s); if (!btn[10].isEnabled()){ for(int i=10;i<=14;i++) btn[i].setEnabled(true); } } }
/** * 成員內部類,負責操作符按鈕的事件處理 */ class OperatorListener implements ActionListener{ public void actionPerformed(ActionEvent e){ if (!append) return; for(int i=10;i<=14;i++) btn[i].setEnabled(false); String s=tf.getText(); long num=Long.parseLong(s);//get the number of textfield append=false; //set append switch(operator){ case '+':result+=num;break; case '-':result-=num;break; case '*':result*=num;break; case '/':{ if (num==0) result=0; else result/=num; break; } case '=':result=num;break; } tf.setText(String.valueOf(result)); //set the value of result to textfield String op=e.getActionCommand(); operator=op.charAt(0); // set operator } } }
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; displayField.setText("" + result); }
public static void main(String[] args) { Calculator calculator = new Calculator(); calculator.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); }
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; displayField.setText("" + result); }
public static void main(String[] args) { Calculator calculator = new Calculator(); calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }