是否可以使用JavaFX更改应用程序图标,还是必须使用Swing?


当前回答

stage.getIcons().add(new Image(ClassLoader.getSystemResourceAsStream("images/icon.png")));

图像文件夹需要在资源文件夹。

其他回答

我试过了,效果不错:

stage.getIcons().add(new Image(getClass().getResourceAsStream("../images/icon.png")));

您可以在fxml中添加它。阶段水平

<icons>
    <Image url="@../../../my_icon.png"/>
</icons>
stage.getIcons().add(new Image(ClassLoader.getSystemResourceAsStream("images/icon.png")));

图像文件夹需要在资源文件夹。

在运行时切换图标:

除了这里的响应,我发现一旦你第一次分配了一个图标到你的应用程序,你不能通过添加一个新图标到你的舞台来切换它(这将有助于你的应用程序的图标从打开/关闭启用/禁用)。

要在运行时设置一个新图标,在尝试添加一个新图标之前使用getIcons().remove(0),其中0是你想覆盖的图标的索引,如下所示:

//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")));

为了从其他方法或类中访问stage,你可以在你的主类中为stage创建一个新的静态字段,这样就可以从start()方法中访问它,通过封装在一个静态方法中,你可以从应用程序的任何地方访问它。

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")));
    }
}

使用这段代码行,您可以轻松地将图标放到应用程序中

stage.getIcons().add(new Image(“image path”) );