programing

JavaFX FXML 컨트롤러 - 생성자 vs 초기화 메서드

procenter 2022. 9. 18. 21:23
반응형

JavaFX FXML 컨트롤러 - 생성자 vs 초기화 메서드

나의Applicationclass는 다음과 같습니다.

public class Test extends Application {

    private static Logger logger = LogManager.getRootLogger();

    @Override
    public void start(Stage primaryStage) throws Exception {

        String resourcePath = "/resources/fxml/MainView.fxml";
        URL location = getClass().getResource(resourcePath);
        FXMLLoader fxmlLoader = new FXMLLoader(location);

        Scene scene = new Scene(fxmlLoader.load(), 500, 500);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

FXMLLoader대응하는 컨트롤러의 인스턴스를 만듭니다( 참조).FXML을 경유하여 철하다.fx:controller디폴트 컨스트럭터를 먼저 호출하고 다음으로 디폴트컨스트럭터를 호출하여initialize방법:

public class MainViewController {

    public MainViewController() {
        System.out.println("first");
    }

    @FXML
    public void initialize() {
        System.out.println("second");
    }
}

출력은 다음과 같습니다.

first
second

그럼 왜?initialize메서드가 존재합니까?컨스트럭터를 사용하는 것과initialize컨트롤러의 초기화를 위한 방법

제안해 주셔서 감사합니다!

한마디로:먼저 생성자를 호출한 다음, any를 호출합니다.@FXML주석이 달린 필드가 입력됩니다.initialize()호출됩니다.

이는 컨스트럭터가 다음 항목에 액세스할 수 없음을 의미합니다.@FXML.fxml 파일에 정의된 컴포넌트를 참조하는 필드,initialize() 접근할 수 있습니다.

FXML 개요에서 인용한 내용:

[...] 컨트롤러는 initialize() 메서드를 정의할 수 있습니다.이 메서드는 관련 문서의 내용이 완전히 로드되면 구현 컨트롤러에서 한 번 호출됩니다.[...] 그러면 구현 클래스는 콘텐츠에 대해 필요한 후 처리를 수행할 수 있습니다.

initialize결국 메서드가 호출됩니다.@FXML주석이 달린 멤버가 주입되었습니다.데이터로 채울 테이블 뷰가 있다고 가정합니다.

class MyController { 
    @FXML
    TableView<MyModel> tableView; 

    public MyController() {
        tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point. 
    }

    @FXML
    public void initialize() {
        tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members. 
    }
}

상기 답변 외에 초기화를 구현하기 위한 레거시 방법이 있을 수 있습니다.fxml 라이브러리에는 Initializable이라는 인터페이스가 있습니다.

import javafx.fxml.Initializable;

class MyController implements Initializable {
    @FXML private TableView<MyModel> tableView;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        tableView.getItems().addAll(getDataFromSource());
    }
}

파라미터:

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. 

그리고 의사들의 메모는 왜 간단한 사용법이@FXML public void initialize()동작:

NOTE이 인터페이스는 컨트롤러에 위치 및 리소스 속성을 자동으로 주입하는 것으로 대체되었습니다.이제 FXMLloader는 컨트롤러에 의해 정의된 적절한 주석이 달린 no-arg initialize() 메서드를 자동으로 호출합니다.가능한 한 주입 방식을 사용할 것을 권장합니다.

언급URL : https://stackoverflow.com/questions/34785417/javafx-fxml-controller-constructor-vs-initialize-method

반응형