如何通过命名空间和FXMLLoader将复杂对象传递到FXML?

我有一个自定义组件。


public class CustomBtn extends Button{

      private ComplexObject properties;

      public void setProperties(ComplexObject properties){
           this.properties = properties;
      }

      public ComplexObject getProperties(){
           return properties
      }

}


public class ComplexObject {
    String x = "hello";
    int y = 42;
}

在FXML中,我可以通过


<Pane xmlns:fx="http://javafx.com/fxml">
  <children>
     <CustomBtn text="hello">
       <properties>
       <!-- here i want to pass the object via namespace placeholder but I don't know how -->
       <properties>
     </CustomBtn>
  </children>
</Pane>

我想通过FXML加载器将对象传递到属性中。


public class SampleAppLauncher extends Application {

    public void start(Stage primaryStage){

        URL val = FXView.class.getclassLoader().getResource("sample.fxml");
        FXMLLoader loader = new FXMLLoader(val);

        Map<String,Object> ns = getNameSpace();
        ComplexObject property = new ComplexObject();
        property.x = "Bye bye";
        property.y = 420;
        // Here is the Object i want to pass
        ns.put("props",property);
        Pane p = loader.load(); 
        Scene s = new Scene(p);
        primaryStage.setScene(s);
        primaryStage.show();

    }

我想通过

传递参数
  

$ {}注释

like:

<Pane xmlns:fx="http://javafx.com/fxml">
  <children>
     <CustomBtn text="hello">
       <properties>
          ${props}
       <properties>
     </CustomBtn>
  </children>
</Pane>

那可能吗?

我知道我可以使用@FXMl之类的“代码隐藏”方法,然后在加载后进行设置。但是我想了解对象是“可传递到名称空间的”对象,以及如何在FXML中配置自定义组件的“更复杂”的对象。 “命名空间映射仅用于“原始值”吗?

cisya 回答:如何通过命名空间和FXMLLoader将复杂对象传递到FXML?

有几个问题:

public class CustomBtn extends Button{

    ...    

    public ComplexObject getProperties(){
        return properties
    }
}

由于Node已经包含具有相同数量参数的方法getProperties,并且从方法返回的类型与Node.getProperties的返回类型不兼容,因此不允许您用您的类中的方法覆盖该方法。您需要为媒体资源选择其他名称。


Map<String,Object> ns = getNameSpace();

该方法名为getNamespace,它是FXMLLoader而不是Application的一部分。您需要将此行更改为

Map<String,Object> ns = loader.getNamespace();

让我们将您的财产名称更改为myProperty

public class CustomBtn extends Button{

      ...

      public void setMyProperty(ComplexObject properties){
           ....
      }

      public ComplexObject getMyProperty(){
           ...
      }
}

您可以使用<fx:reference>通过fxml插入属性:

 <CustomBtn text="hello">
   <myProperty>
     <fx:reference source="props"/>
   <myProperty>
 </CustomBtn>

或者使用以$开头的属性:

 <CustomBtn text="hello" myProperty="$props" />
本文链接:https://www.f2er.com/3160564.html

大家都在问