javafx NullPointerException with controlsfx Notifications componnets

£可爱£侵袭症+ 提交于 2019-12-01 20:39:19

I realize that this exception occurs when the stage go to hide mode and the notification component cannot find stage when notification needs to show in stage. After searching in internet I find two solution for this problem.

Solution 1:

Open the stage and show notification. In this way we should check that if the stage was hidden, open it , and show notification. To do this we must add this condition in CreateNotification Method:

Stage stage = (Stage)  button.getScene().getWindow();
     if (!stage.isShowing()){
             stage.show();
     }

Solution 2:

In this solution we create a dummy stage and set its opacity to zero and after that, hide the main stage. I find this solution at this link and put the code in here:

public void createDummyStage() {
    Stage dummyPopup = new Stage();
    dummyPopup.initModality(Modality.NONE);
    // set as utility so no iconification occurs
    dummyPopup.initStyle(StageStyle.UTILITY);
    // set opacity so the window cannot be seen
    dummyPopup.setOpacity(0d);
    // not necessary, but this will move the dummy stage off the screen
    final Screen screen = Screen.getPrimary();
    final Rectangle2D bounds = screen.getVisualBounds();
    dummyPopup.setX(bounds.getMaxX());
    dummyPopup.setY(bounds.getMaxY());
    // create/add a transparent scene
    final Group root = new Group();
    dummyPopup.setScene(new Scene(root, 1d, 1d, Color.TRANSPARENT));
    // show the dummy stage
    dummyPopup.show();
}

As I mention bellow, We should call this method before hiding the main stage:

 @FXML
public void handleSysTryAction(ActionEvent event) {
    Stage stage = (Stage) button.getScene().getWindow();
    createDummyStage();
    stage.hide();
}

I implement this two solution and every things works well. If you have a better solution for this problem please put here

You can download the complete Netbeans project from my Dropbox

I could not figure out why hamid's first solution was not working for me, until I debugged the Notifications creation. I found out, that beside the need of the Window to be isShowing it has to be isFocused too!

My solution is to call something like this method before Notifications.show():

private void focusStage() {
    final Stage stage = (Stage) button.getScene().getWindow();
    if (!stage.isShowing()) {
        stage.show();
    }
    if (!stage.isFocused()) {
        stage.requestFocus();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!