Javafx - toggle between AlwaysonTop

45 Views Asked by At

I want an option to toggle between alwaysontop true/false. But when I close and then show the window it does not take it over.

    @FXML
    public void toggleAlwaysonTop(ActionEvent event){
        try{
            Worker.toggleAlwaysOnTop(); //changes boolean if it is always on top and saves it log
            Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow(); //gets stage of settings window
            Stage changer = Application.getPrimaryStage(); //gets primary stage of the Application
            stage.close();
            changer.close();
            changer.show();

            
        }catch (Exception e) {
            System.out.println("Error bei der App Klicken von ModeButton. \n error is: "+e);
        e.printStackTrace();
        }
    }

In the Application class I use:

primaryStage.setAlwaysOnTop(Worker.isItalwaysOnTop);

For the second Window does it work when i open it again via button. But If I use stage.close() and stage.show() I have the same problem. I use a similar method to toggle between Dark/Light Mode. Here it works perfectly.

1

There are 1 best solutions below

0
On

Oh it was actually easy you have just to use stage.setAlwaysOnTop(); and changer.requestFocus(); (to take over directly)

   @FXML
    public void toggleAlwaysonTop(ActionEvent event){
        try{
            Worker.toggleAlwaysOnTop(); //changes boolean if it is always on top and saves it log
            Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow(); //gets stage of settings window
            Stage changer = Application.getPrimaryStage(); //gets primary stage of the Application
            stage.close();
            changer.setAlwaysOnTop(Worker.isItalwaysOnTop);
            changer.requestFocus();//Preventing that it does not take it over directly when you worked in another application before (sry I can't explain the Problem properly^^)

            
        }catch (Exception e) {
            System.out.println("Error bei der App Klicken von ModeButton. \n error is: "+e);
        e.printStackTrace();
        }
    }