2012-10-24 43 views
0

读完introduction_to_fxml之后,我得到一个印象,即initialize方法可以用作spring的afterPropertiesSet或EJB的@PostConstruct方法 - 期望所有成员变量在被调用时设置。但是当我尝试时,我得到了NPE。我尝试的代码如下所示。初始化中的NPE

主要应用:

public class MyApp extends Application { 

    @Override 
    public void start(Stage stage) throws Exception { 
     Parent root = FXMLLoader.load(getClass().getResource("/myapp.fxml"));///MAIN LOAD 

     Scene scene = new Scene(root, 320, 240); 
     scene.getStylesheets().add("/myapp.css"); 
     stage.setScene(scene); 
     stage.setTitle("my app"); 
     stage.show(); 
    } 

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

myapp.fxml:

... 
<VBox fx:id="root" xmlns:fx="http://javafx.com/fxml" > 
     <ControlA> 
      <SomeClass>  
      </SomeClass> 
     </ControlA> 
</VBox> 

ControlA.java:

@DefaultProperty("aproperty") 
public class ControlA extends StackPane { 
    private SomeClass aproperty; 

    public ContentPane(){ 
     try { 
      FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/controls/ControlA.fxml")); 
      fxmlLoader.setRoot(this); 
      fxmlLoader.setController(this); 

      fxmlLoader.load();//ControlA LOAD 

     } catch (IOException exception) { 
      throw new RuntimeException(exception); 
     } 
    } 

    public void initialize() { 
     //aproperty is null here, called from ControlA LOAD 
    } 

    //aproperty get/set 
    public void setAproperty(SomeClass p){//it is called from MAIN LOAD 
    .... 
} 

该组件的初始化方法是从它的负载方法调用,并且它的属性是从稍后调用的父装载方法设置。它看起来很容易理解,在读取父fxml之前,组件的属性值不能构造。但是如果是这样的话,在组件初始化之前初始化一个组件的最佳实践是什么?

最好的问候,尤金。

回答

0

您需要在控制器中实现接口Initializable。我的印象是这只适用于控制器。