JavaFX Application Icon

后端 未结 17 1726
滥情空心
滥情空心 2020-11-28 02:25

Is it possible to change the application icon using JavaFX, or does it have to be done using Swing?

17条回答
  •  感动是毒
    2020-11-28 02:43

    Toggle icons in runtime:

    In addition to the responses here, I found that once you have assigned an Icon to your application by the first time you cannot toggle it by just adding a new icon to your stage (this would be helpful if you need to toggle the icon of your app from on/off enabled/disabled).

    To set a new icon during run time use the getIcons().remove(0) before trying to add a new icon, where 0 is the index of the icon you want to override like is shown here:

    //Setting icon by first time (You can do this on your start method).
    stage.getIcons().add(new Image(getClass().getResourceAsStream("enabled.png")));
    
    //Overriding app icon with a new status (This can be in another method)
    stage.getIcons().remove(0);
    stage.getIcons().add(new Image(getClass().getResourceAsStream("disabled.png")));
    

    To access the stage from other methods or classes you can create a new static field for stage in you main class so can access it from out of the start() method by encapsulating in on a static method that you can access from anywhere in your app.

    public class MainApp extends Application {
        private static Stage stage;
        public static Stage getStage() { return stage; }
    
        @Override public void start(Stage primaryStage) {
            stage = primaryStage
            stage.getIcons().add(new Image(getClass().getResourceAsStream("enabled.png")));
        }
    }
    
    public class AnotherClass {
        public void setStageTitle(String newTitle) {
            MainApp.getStage().setTitle(newTitle);
            MainApp.getStage().getIcons().remove(0);
            MainApp.getStage().getIcons().add(new Image(getClass().getResourceAsStream("disabled.png")));
        }
    }
    

提交回复
热议问题