2017-10-08 11 views
1

특정 대화 상자를 만드는 일반적인 방법을 만들고 싶습니다.Javafx로 일반 Dialog 메서드 만들기

private void setDialog(String dialog,String title){ 
    try { 
     // Load the fxml file and create a new stage for the popup 
     FXMLLoader loader = new FXMLLoader(Main.class.getResource("/view/" + dialog + ".fxml")); 
     AnchorPane page = (AnchorPane) loader.load(); 
     Stage dialogStage = new Stage(); 
     dialogStage.setTitle(title); 
     dialogStage.initModality(Modality.WINDOW_MODAL); 
     dialogStage.initOwner(Main.getPs()); 
     Scene scene = new Scene(page); 
     dialogStage.setScene(scene); 


    loader.getController().setDialogStage(dialogStage); 

     // Show the dialog and wait until the user closes it 
     dialogStage.showAndWait(); 


     } catch (IOException e) { 
     // Exception gets thrown if the fxml file could not be loaded 
     e.printStackTrace(); 
     } 

} 

하지만이 줄

loader.getController().setDialogStage(dialogStage) 

에 오류가 정확히 실수는 내가 그것을 어떻게 해결합니까이

"The method setDialogStage(Stage) is undefined for the type Object" 

입니까? 고맙습니다.

나는별로 경험이 없습니다. 즉, 당신이 정말 간단한 캐스팅보다 더 형태 보증하지

loader.<MyController>getController().setDialogStage(dialogStage); 

을 할 수

답변

1

당신이 setDialogStage(Stage) 방법을 정의하는 일부 컨트롤러 클래스 MyController이 가정 말한다; 컨트롤러가 올바른 유형이 아닌 경우 런타임시 ClassCastException으로 실패합니다.

public interface DialogController { 

    public void setDialogStage(Stage dialogStage); 

} 

귀하의 컨트롤러가

public class MyController implements DialogController { 

    // ... 

    @Override 
    public void setDialogStage(Stage dialogStage) { 
     // ... 
    } 

} 

같이 :

이 방법이있을 수 있습니다 여러 컨트롤러가있는 경우, 최선의 선택은 그들에게 적절한 방법을 정의하는 인터페이스를 구현하기 위해 아마 컨트롤러를 일반용으로 만 취급하면됩니다. DialogController :

loader.<DialogController>getController().setDialogStage(dialogStage); 
1

자신 만의 대화 메커니즘을 만드는 데는 충분한 이유가있을 수 있지만, JavaFX에는 이미 대화 상자에 standard way이 있다는 것을 지적하고자합니다.

웹 사이트 code.makery

는 대화 상자를 만드는 방법에 대한 몇 가지 예를 보여줍니다

Alert alert = new Alert(AlertType.CONFIRMATION); 
alert.setTitle("Confirmation Dialog"); 
alert.setHeaderText("Look, a Confirmation Dialog"); 
alert.setContentText("Are you ok with this?"); 

Optional<ButtonType> result = alert.showAndWait(); 
if (result.get() == ButtonType.OK){ 
    // ... user chose OK 
} else { 
    // ... user chose CANCEL or closed the dialog 
} 

Confirmation dialog

당신은 또한 사용자 정의 컨텐츠 대화 상자를 만들 수 있습니다 Exception Dialog