Concatenate Javafx fx:Id

后端 未结 2 1394

I\'m kinda new to JavaFX and currently trying to do a Calendar application for a school project. I was wondering if there was a way to concatenate a fx:id

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-27 02:50

    In addition to the methods mentioned by @jewelsea here are 2 more ways to do this:

    1. Create & inject a Map containing the boxes as values from the fxml:

      
          
              

      Controller

      public class Controller {
      
          private Map boxes;
          @FXML
          private Spinner number;
          @FXML
          private Label box1;
          @FXML
          private Label box2;
      
          @FXML
          private void modify(ActionEvent event) {
              boxes.get("box"+number.getValue()).setText("42");
          }
      
      }
      
    2. Pass the namespace of the FXMLLoader, which is a Map mapping fx:ids to the associated Objects, to the controller:

      
          
              

      Controller

      public class Controller implements NamespaceReceiver {
      
          private Map namespace;
          @FXML
          private Spinner number;
          @FXML
          private Label box1;
          @FXML
          private Label box2;
      
          @FXML
          private void modify(ActionEvent event) {
              ((Label)namespace.get("box" + number.getValue())).setText("42");
          }
      
          @Override
          public void setNamespace(Map namespace) {
              this.namespace = namespace;
          }
      }
      
      public interface NamespaceReceiver {
          public void setNamespace(Map namespace);
      }
      

      Code for loading the fxml:

      public static  T load(URL url) throws IOException {
          FXMLLoader loader = new FXMLLoader(url);
          T result = loader.load();
          Object controller = loader.getController();
          if (controller instanceof NamespaceReceiver) {
              ((NamespaceReceiver) controller).setNamespace(loader.getNamespace());
          }
          return result;
      }
      

提交回复
热议问题