2017-04-19 46 views
2

如何在不使用alert.initOwner()的情况下将程序图标设置为提醒? 为什么没有initOwner?这是因为在整个窗口初始化之前必须显示一些警报,所以没有可以使用initOwner函数的场景。JavaFX 8如何设置程序图标以提醒?

回答

2

您可以从Alert实例中窃取DialogPane,并将其添加到常规舞台。一个节点只能是一次一个场景的根,所以你需要先更换警报的场景的根:

public class AlertWithIcon 
extends Application { 
    @Override 
    public void start(Stage stage) { 
     Alert alert = new Alert(Alert.AlertType.CONFIRMATION, 
      "Are you sure you want to delete this item?", 
      ButtonType.YES, ButtonType.NO); 
     alert.setHeaderText("Delete Item"); 

     DialogPane pane = alert.getDialogPane(); 

     ObjectProperty<ButtonType> result = new SimpleObjectProperty<>(); 
     for (ButtonType type : pane.getButtonTypes()) { 
      ButtonType resultValue = type; 
      ((Button) pane.lookupButton(type)).setOnAction(e -> { 
       result.set(resultValue); 
       pane.getScene().getWindow().hide(); 
      }); 
     } 

     pane.getScene().setRoot(new Label()); 
     Scene scene = new Scene(pane); 

     Stage dialog = new Stage(); 
     dialog.setScene(scene); 
     dialog.setTitle("Delete Item"); 
     dialog.getIcons().add(new Image("GenericApp.png")); 

     result.set(null); 
     dialog.showAndWait(); 

     System.out.println("Result is " + result); 
    } 
} 
+0

不错!这是我一直在寻找的东西,谢谢:D –

2
public class AlertWithIcon 
extends Application { 
    @Override 
    public void start(Stage stage) { 
     Alert alert = new Alert(Alert.AlertType.CONFIRMATION, 
      "Are you sure you want to delete this item?", 
     ButtonType.YES, ButtonType.NO);  
     alert.setHeaderText("Delete Item"); 
    ((Stage)alert.getDialogPane().getScene().getWindow()).getIcons().add(new image("GenericApp.png")); 
    alert.showAndWait(); 
} 
} 
0

这是它是如何做:

// Get the Stage. 
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow(); 

// Add a custom icon. 
stage.getIcons().stage.getIcons().add(new Image("images/logo_full3.png")); 

上面的图片引用可能有问题。但是,只要它能够工作,您就可以尝试进行配置。这是我的方式(我使用maven)。如果你不使用maven,你的可能会有所不同。

完整教程在这里:Alert javafx tutorial