SOLUTION public class Calculator extends JFrame implements Action
SOLUTION public class Calculator extends JFrame implements Action. Listener { private JPanel panel; private JText. Field display; private JButton[] buttons; private String[] labels = { "Backspace", "", "CE", "C", "7", "8", "9", "/", "sqrt", "4", "5", "6", "x", "%", "1", "2", "3", "-", "1/x", "0", "-/+", "+", "=", }; private double result = 0; private String operator = "="; private boolean start. Of. Number = true; public Calculator() { display = new JText. Field(35); panel = new JPanel(); display. set. Text("0. 0"); //display. set. Enabled(true);
panel. set. Layout(new Grid. Layout(0, 5, 3, 3)); buttons = new JButton[25]; int index = 0; for (int rows = 0; rows < 5; rows++) { for (int cols = 0; cols < 5; cols++) { buttons[index] = new JButton(labels[index]); if (cols >= 3) SOLUTION buttons[index]. set. Foreground(Color. red); else buttons[index]. set. Foreground(Color. blue); buttons[index]. set. Background(Color. yellow); panel. add(buttons[index]); buttons[index]. add. Action. Listener(this); index++; } } add(display, Border. Layout. NORTH); add(panel, Border. Layout. CENTER); set. Visible(true); pack(); }
public void action. Performed(Action. Event e) { String command = e. get. Action. Command(); if (command. char. At(0) == 'C') { start. Of. Number = true; result = 0; operator = "="; display. set. Text("0. 0"); } else if (command. char. At(0) >= '0' && command. char. At(0) <= '9' || command. equals(". ")) { if (start. Of. Number == true) display. set. Text(command); else display. set. Text(display. get. Text() + command); start. Of. Number = false; } else { if (start. Of. Number) { if (command. equals("-")) { display. set. Text(command); start. Of. Number = false; } else operator = command; } else { double x = Double. parse. Double(display. get. Text()); calculate(x); operator = command; start. Of. Number = true; } } } SOLUTION
SOLUTION private void calculate(double n) { if (operator. equals("+")) result += n; else if (operator. equals("-")) result -= n; else if (operator. equals("*")) result *= n; else if (operator. equals("/")) result /= n; else if (operator. equals("=")) result = n; display. set. Text("" + result); } public static void main(String args[]) { Calculator s = new Calculator(); } }
Q & A
- Slides: 7