欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaFX学习之样例6 博客分类: javafx分享 javafx计算器 

程序员文章站 2024-02-28 22:32:04
...
  该代码实现的一个最简单的计算器
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import java.util.HashMap;
import java.util.Map;

// a simple JavaFX calculator.
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的风格,这里stage只有关闭按钮
    stage.setResizable(false);
    stage.setScene(new Scene(createLayout(screen, buttons)));
    stage.show();
  }

  //root使用的VBox,上面text。下面按钮,按钮使用的是瓦片布局,一块接一块,满了换行。
  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));    //绑定text的值
    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;
  }

  //根据s把对应的加减乘除存放进到triigerOp
  private ObjectProperty<Op> determineOperand(String s) {
    final ObjectProperty<Op> triggerOp = new SimpleObjectProperty(Op.NOOP);
    switch (s.charAt(0)) {
      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();
      }
    });
  }

  //创建一个标准的button
  private Button makeStandardButton(String s) {
    Button button = new Button(s);
    button.setStyle("-fx-base: beige;");
    accelerators.put(s, button);  //这些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));  //没有输加减乘除时,前一数字*10
        } 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;
        }
      }
    });
  }
}

关于fx,学习到了button.fire()方法的使用,也就是调用button的action事件。
相关标签: javafx 计算器