【问题标题】:JavaFX without controller specified未指定控制器的 JavaFX
【发布时间】:2018-03-18 14:10:57
【问题描述】:

我想删除 onAction 以分离我的视图和我的控制器

这是 javaFx 代码:

    <HBox spacing="10" alignment="CENTER">
        <Button text="7" prefWidth="50" font="$FONT" onAction="#Nombre" />
        <Button text="8" prefWidth="50" font="$FONT" onAction="#Nombre" />
        <Button text="9" prefWidth="50" font="$FONT" onAction="#Nombre" />
        <Button text="/" prefWidth="50" font="$FONT" onAction="#Operateur" />
    </HBox>

我想将按钮上的 id 与我的控制器相关联

谢谢

【问题讨论】:

标签: java model-view-controller javafx


【解决方案1】:

您可以将 Nombre 按钮提取到它们自己的类中:

class NombreButton extends Button {

    public NombreButton() {
        this.setOnAction(this::nombre);
    }

    private void nombre(ActionEvent actionEvent) {
        // Your action here
    }

}

然后在您的视图中像常规按钮一样使用它们。

<HBox spacing="10" alignment="CENTER">
    <NombreButton text="7" prefWidth="50" font="$FONT" />
    <NombreButton text="8" prefWidth="50" font="$FONT" />
    <NombreButton text="9" prefWidth="50" font="$FONT" />
</HBox>

【讨论】:

    【解决方案2】:

    删除action并添加id(不要忘记fx的xmlns):

    <HBox spacing="10" alignment="CENTER" xmlns:fx="http://javafx.com/fxml/1">
        <Button fx:id="bNumber7" text="7" prefWidth="50" font="$FONT" />
        <Button fx:id="bNumber8" text="8" prefWidth="50" font="$FONT" />
        <Button fx:id="bNumber9" text="9" prefWidth="50" font="$FONT" />
        <Button fx:id="bDivide" text="/" prefWidth="50" font="$FONT" />
    </HBox>
    

    然后,在你的控制器中:

    public Calculator {
    
        @FXML
        private Button bNumber7;
    
        @FXML
        private Button bNumber8;
    
        @FXML
        private Button bNumber9;
    
        private HBox component;
    
        /**
        * Constructor.
        */
        public void Calculator() {
           // Load your fxml.
           FXMLLoader loader = new FXMLLoader(getClass().getResources("YourFxmlPath.fxml"));
           // Set this class as controller of the view.
           loader.setController(this);
           try {
              component = (HBox)loader.load();
           } catch(IOException e) {
              System.out.println("An error occurs trying to load the FXML : "+ e);
           }
        }
    
        @FXML 
        private void initialize() {
           bNumber7.setOnMouseClicked(e -> {
              System.out.println("Clicked on 7 button.");
              // Do your stuff
           });
    
           // Add listener on other buttons if needed.
    
           bDivide.setOnMouseClicked(e -> {
              System.out.println("Clicked on 7 button.");
              // Do your stuff
           });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2016-05-30
      • 2019-11-23
      • 2016-11-12
      • 2017-06-02
      • 2017-01-01
      相关资源
      最近更新 更多