You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Calc.java 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package com.vaadin.demo;
  2. import com.vaadin.ui.Button;
  3. import com.vaadin.ui.GridLayout;
  4. import com.vaadin.ui.Label;
  5. import com.vaadin.ui.Window;
  6. // Calculator is created by extending Application-class. Application is
  7. // deployed by adding ApplicationServlet to web.xml and this class as
  8. // "application" parameter to the servlet.
  9. public class Calc extends com.vaadin.Application {
  10. // Calculation data model is automatically stored in the user session
  11. private double current = 0.0;
  12. private double stored = 0.0;
  13. private char lastOperationRequested = 'C';
  14. // User interface components
  15. private final Label display = new Label("0.0");
  16. private final GridLayout layout = new GridLayout(4, 5);
  17. // Application initialization creates UI and connects it to business logic
  18. @Override
  19. public void init() {
  20. // Place the layout to the browser main window
  21. setMainWindow(new Window("Calculator Application", layout));
  22. // Create and add the components to the layout
  23. layout.addComponent(display, 0, 0, 3, 0);
  24. for (String caption : new String[] { "7", "8", "9", "/", "4", "5", "6",
  25. "*", "1", "2", "3", "-", "0", "=", "C", "+" }) {
  26. Button button = new Button(caption, new Button.ClickListener() {
  27. public void buttonClick(Button.ClickEvent event) {
  28. // On button click, calculate and show the result
  29. display.setValue(calculate(event.getButton()));
  30. }
  31. });
  32. layout.addComponent(button);
  33. }
  34. }
  35. // Calculator "business logic" implemented here to keep the example minimal
  36. private double calculate(Button buttonClicked) {
  37. char requestedOperation = buttonClicked.getCaption().charAt(0);
  38. if ('0' <= requestedOperation && requestedOperation <= '9') {
  39. current = current * 10
  40. + Double.parseDouble("" + requestedOperation);
  41. return current;
  42. }
  43. switch (lastOperationRequested) {
  44. case '+':
  45. stored += current;
  46. break;
  47. case '-':
  48. stored -= current;
  49. break;
  50. case '/':
  51. stored /= current;
  52. break;
  53. case '*':
  54. stored *= current;
  55. break;
  56. case 'C':
  57. stored = current;
  58. break;
  59. }
  60. lastOperationRequested = requestedOperation;
  61. current = 0.0;
  62. if (requestedOperation == 'C') {
  63. stored = 0.0;
  64. }
  65. return stored;
  66. }
  67. }