JavaFX FXML controller - constructor vs initialize method

后端 未结 3 549
忘了有多久
忘了有多久 2020-11-22 12:33

My Application class looks like this:

public class Test extends Application {

    private static Logger logger = LogManager.getRootLogger();

          


        
3条回答
  •  [愿得一人]
    2020-11-22 12:57

    In Addition to the above answers, there probably should be noted that there is a legacy way to implement the initialization. There is an interface called Initializable from the fxml library.

    import javafx.fxml.Initializable;
    
    class MyController implements Initializable {
        @FXML private TableView tableView;
    
        @Override
        public void initialize(URL location, ResourceBundle resources) {
            tableView.getItems().addAll(getDataFromSource());
        }
    }
    

    Parameters:

    location - The location used to resolve relative paths for the root object, or null if the location is not known.
    resources - The resources used to localize the root object, or null if the root object was not localized. 
    

    And the note of the docs why the simple way of using @FXML public void initialize() works:

    NOTE This interface has been superseded by automatic injection of location and resources properties into the controller. FXMLLoader will now automatically call any suitably annotated no-arg initialize() method defined by the controller. It is recommended that the injection approach be used whenever possible.

提交回复
热议问题