1. Home
  2. Lập Trình
  3. Code Calculator JavaFx Application Và JavaFx FXML Application
Nguyễn Tuấn 4 năm trước

Code Calculator JavaFx Application Và JavaFx FXML Application

Calculator JavaFx nay code trên javafx và javafx fxml thử nhỉ, trên mỗi nền tảng có 1 cách code khác nhau. Nhưng thuật toán thì cơ bản cũng giống nhau mà thôi. Mong bài này sẽ giúp được bạn trong quá trình tìm hiểu javafx hay javafx fxml nhé. Xem nhiều hơn tại đây nhé.

Calculator JavaFx Demo 1


public class JavaFXApplication4 extends Application {
    
    private TextField txtX = new TextField();
    private TextField txtY = new TextField();
    private TextField txtAns = new TextField();
    private Label lbX = new Label("X");
    private Label lbY = new Label("Y");
    private Label lbAns = new Label("Ans");
    private VBox vbLeft = new VBox();
    private VBox vbRight = new VBox();
    private BorderPane paneTop = new BorderPane();
    private BorderPane paneContent = new BorderPane();
    private Button[] bt = new Button[16];
    private GridPane contentLeft = new GridPane();
    private VBox contentRight = new VBox();
    private RadioButton radioBTX = new RadioButton("X");
    private RadioButton radioBTY = new RadioButton("Y");
    private String[] labelBT = {
        "7", "8", "9", "/",
        "4", "5", "6", "*",
        "1", "2", "3", "+",
        "C", "0", "=", "-"
    };
    private float result;
    private int X;
    private int Y;
    private String inputNum = "0";
    private String inputNumX = "0";
    private String inputNumY = "0";
    private String status = "";
    private String operator = "";
    public void compute(int X, int Y, String operator)
    {
        float x = (float)X;
        float y = (float)Y;
        if(operator.equals("+"))
        {
            result = x + y;
            txtAns.setText(Float.toString(result));
        }
        if(operator.equals("-"))
        {
            result = x - y;
            txtAns.setText(Float.toString(result));
        }
        if(operator.equals("*"))
        {
            result = x * y;
            txtAns.setText(Float.toString(result));
        }
        if(operator.equals("/"))
        {
            result = x / y;
            txtAns.setText(Float.toString(result));
        }
            
    }
   
     
    EventHandler handler = event -> {
         String currentBtnLabel = ((Button)event.getSource()).getText();
         Alert alert = new Alert(AlertType.INFORMATION);
         switch(currentBtnLabel)
         {
            case "0": case "1": case "2": case "3": case "4":
            case "5": case "6": case "7": case "8": case "9":
            {
                if(inputNum.equals("0"))
                    inputNum = currentBtnLabel;
                else
                    inputNum += currentBtnLabel;
                if(status.equals("X"))
                {
                    inputNumX = inputNum;
                    inputNumY = "0";
                    txtX.setText(inputNumX);
                }
                else if(status.equals("Y"))
                {
                    inputNumY = inputNum;
                    inputNumX = "0";
                    txtY.setText(inputNumY);
                }
                break;
            }
            
              case"+":
              {
                  operator = "+";
                  break;
              }
              case"-":
              {
                  operator = "-";
                  break;
              }
              case"*":
              {
                  operator = "*";
                  break;
              }
              case"/":
              {
                  operator = "/";
                  break;
              }
              case"=":
              {
                  int x = Integer.parseInt(txtX.getText());
                  int y = Integer.parseInt(txtY.getText());
                  if(y == 0){
                    alert.setTitle("Message Here...");
                    alert.setHeaderText("Lỗi Rồi Nhé");
                    alert.setContentText("Chia cho số khác thử đi");
                    alert.showAndWait().ifPresent(rs -> {
                        if (rs == ButtonType.OK) {
                            System.out.println("OK");
                        }
                    });
                  }else
                    compute(x, y, operator);
                  break;
              }
              case"C":
              {
                  txtX.setText("");
                  txtY.setText("");
                  txtAns.setText("");
                  inputNum = "0";
                  inputNumX = "0";
                  inputNumY = "0";
              }
         }
     };
    
    @Override
    public void start(Stage primaryStage) {
        txtX.setEditable(false);
        txtY.setEditable(false);
        vbLeft.getChildren().add(txtX);
        vbLeft.getChildren().add(txtY);
        vbLeft.getChildren().add(txtAns);
        vbRight.getChildren().add(lbX);
        vbRight.getChildren().add(lbY);
        vbRight.getChildren().add(lbAns);
        vbRight.setPadding(new Insets(0, 85, 0, 0));
        vbRight.setAlignment(Pos.CENTER);
        vbRight.setSpacing(8);
        paneTop.setLeft(vbLeft);
        paneTop.setRight(vbRight);
        
  
        for(int i = 0; i < labelBT.length; i++)
        {
            bt[i] = new Button(labelBT[i]);
            bt[i].setOnAction(handler);
            bt[i].setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
            contentLeft.add(bt[i], i%4, i/4);
        }
        contentLeft.setVgap(10);
        contentLeft.setHgap(10);
        contentRight.getChildren().add(radioBTX);
        contentRight.getChildren().add(radioBTY);
        contentRight.setPadding(new Insets(0, 80, 0, 0));
        
        ToggleGroup tg = new ToggleGroup();
        radioBTX.setToggleGroup(tg);
        radioBTX.setUserData("X");
        radioBTY.setToggleGroup(tg);
        radioBTY.setUserData("Y");
        
        tg.selectedToggleProperty().addListener(new ChangeListener<Toggle>(){
            @Override
            public void changed(ObservableValue<? extends Toggle> observable, Toggle oldValue, Toggle newValue) {
                if(tg.getSelectedToggle() != null)
                {
                    status = tg.getSelectedToggle().getUserData().toString();
                    if(status == "X")
                    {
                        inputNum = "0";
                        txtX.setEditable(true);
                        txtY.setEditable(false);
                    }
                    else
                    {   inputNum = "0";
                        txtY.setEditable(true);
                        txtX.setEditable(false);
                    }
                } 
            }
        
    });
        
        
         
        
        paneContent.setMinSize(200, 200);
        paneContent.setRight(contentRight);
        paneContent.setLeft(contentLeft);
        paneContent.setMinHeight(200);
        
        BorderPane root = new BorderPane();
        root.setPadding(new Insets(5, 5, 5, 5));
        root.setTop(paneTop);    
        root.setCenter(paneContent);
         // Set up scene and stage
        primaryStage.setScene(new Scene(root, 300, 220));
        primaryStage.setTitle("JavaFX Calculator");
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
}

Calculator JavaFx Demo 2

Calculator JavaFx Fxml
Calculator JavaFx Fxml

public class Calc extends Application {
  private static final String[][] template = {
      { "7", "8", "9", "/" },
      { "4", "5", "6", "*" },
      { "1", "2", "3", "-" },
      { "0", "c", "=", "+" }
  };

  private final Map<String, Button> accelerators = new HashMap<>();

  private DoubleProperty stackValue = new SimpleDoubleProperty();
  private DoubleProperty value = new SimpleDoubleProperty();

  private enum Op { NOOP, ADD, SUBTRACT, MULTIPLY, DIVIDE }

  private Op curOp   = Op.NOOP;
  private Op stackOp = Op.NOOP;

  public static void main(String[] args) { launch(args); }

  @Override public void start(Stage stage) {
    final TextField screen  = createScreen();
    final TilePane  buttons = createButtons();

    stage.setTitle("Calc");
    stage.initStyle(StageStyle.UTILITY);
    stage.setResizable(false);
    stage.setScene(new Scene(createLayout(screen, buttons)));
    stage.show();
  }

  private VBox createLayout(TextField screen, TilePane buttons) {
    final VBox layout = new VBox(20);
    layout.setAlignment(Pos.CENTER);
    layout.setStyle("-fx-background-color: chocolate; -fx-padding: 20; -fx-font-size: 20;");
    layout.getChildren().setAll(screen, buttons);
    handleAccelerators(layout);
    screen.prefWidthProperty().bind(buttons.widthProperty());
    return layout;
  }

  private void handleAccelerators(VBox layout) {
    layout.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
      @Override
      public void handle(KeyEvent keyEvent) {
        Button activated = accelerators.get(keyEvent.getText());
        if (activated != null) {
          activated.fire();
        }
      }
    });
  }

  private TextField createScreen() {
    final TextField screen = new TextField();
    screen.setStyle("-fx-background-color: aquamarine;");
    screen.setAlignment(Pos.CENTER_RIGHT);
    screen.setEditable(false);
    screen.textProperty().bind(Bindings.format("%.0f", value));
    return screen;
  }

  private TilePane createButtons() {
    TilePane buttons = new TilePane();
    buttons.setVgap(7);
    buttons.setHgap(7);
    buttons.setPrefColumns(template[0].length);
    for (String[] r: template) {
      for (String s: r) {
        buttons.getChildren().add(createButton(s));
      }
    }
    return buttons;
  }

  private Button createButton(final String s) {
    Button button = makeStandardButton(s);

    if (s.matches("[0-9]")) {
      makeNumericButton(s, button);
    } else {
      final ObjectProperty<Op> triggerOp = determineOperand(s);
      if (triggerOp.get() != Op.NOOP) {
        makeOperandButton(button, triggerOp);
      } else if ("c".equals(s)) {
        makeClearButton(button);
      } else if ("=".equals(s)) {
        makeEqualsButton(button);
      }
    }

    return button;
  }

  private ObjectProperty<Op> determineOperand(String s) {
    final ObjectProperty<Op> triggerOp = new SimpleObjectProperty<>(Op.NOOP);
    switch (s) {
      case "+": triggerOp.set(Op.ADD);      break;
      case "-": triggerOp.set(Op.SUBTRACT); break;
      case "*": triggerOp.set(Op.MULTIPLY); break;
      case "/": triggerOp.set(Op.DIVIDE);   break;
    }
    return triggerOp;
  }

  private void makeOperandButton(Button button, final ObjectProperty<Op> triggerOp) {
    button.setStyle("-fx-base: lightgray;");
    button.setOnAction(new EventHandler<ActionEvent>() {
      @Override
      public void handle(ActionEvent actionEvent) {
        curOp = triggerOp.get();
      }
    });
  }

  private Button makeStandardButton(String s) {
    Button button = new Button(s);
    button.setStyle("-fx-base: beige;");
    accelerators.put(s, button);
    button.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
    return button;
  }

  private void makeNumericButton(final String s, Button button) {
    button.setOnAction(new EventHandler<ActionEvent>() {
      @Override
      public void handle(ActionEvent actionEvent) {
        if (curOp == Op.NOOP) {
          value.set(value.get() * 10 + Integer.parseInt(s));
        } else {
          stackValue.set(value.get());
          value.set(Integer.parseInt(s));
          stackOp = curOp;
          curOp = Op.NOOP;
        }
      }
    });
  }

  private void makeClearButton(Button button) {
    button.setStyle("-fx-base: mistyrose;");
    button.setOnAction(new EventHandler<ActionEvent>() {
      @Override
      public void handle(ActionEvent actionEvent) {
        value.set(0);
      }
    });
  }

  private void makeEqualsButton(Button button) {
    button.setStyle("-fx-base: ghostwhite;");
    button.setOnAction(new EventHandler<ActionEvent>() {
      @Override
      public void handle(ActionEvent actionEvent) {
        switch (stackOp) {
          case ADD:      value.set(stackValue.get() + value.get()); break;
          case SUBTRACT: value.set(stackValue.get() - value.get()); break;
          case MULTIPLY: value.set(stackValue.get() * value.get()); break;
          case DIVIDE:   value.set(stackValue.get() / value.get()); break;
        }
      }
    });
  }
}

Calculator JavaFx Fxml Demo 3

Calculator JavaFx
Calculator JavaFx

Cảm ơn các bạn đã ghé thăm. Chúc các bạn thành công!

4 lượt xem | 0 bình luận