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


当前回答

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

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

其他回答

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

<icons>
    <Image url="@../../../my_icon.png"/>
</icons>

你认为如何创建新的包,即图像。图标在你的SRC目录和移动到那里你。png图像?那么你只需要写:

Image image = new Image("/image/icons/nameOfImage.png");
primaryStage.getIcons().add(image);

这个解决方案非常适合我,但我仍然不确定它是否正确(这里是初学者)。

如果运行jar文件,Michael Berry指定的代码将改变标题栏和任务栏中的图标。快捷图标不可更改。

如果你运行一个用com编译的本地程序。zenjava,你必须添加一个链接到程序图标:

<plugin>
    <groupId>com.zenjava</groupId>
    <artifactId>javafx-maven-plugin</artifactId>
    <version>8.8.3</version>
    <configuration>
    ...
        <bundleArguments>
            <icon>${project.basedir}/src/main/resources/images/filename.ico</icon>
        </bundleArguments>
    </configuration>
</plugin>

这将为快捷方式和任务栏添加一个图标。

stage.getIcons().add(new Image("/images/logo_only.png"));

在src文件夹中创建图像文件夹并从中获取图像是一个好习惯。

在运行时切换图标:

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

要在运行时设置一个新图标,在尝试添加一个新图标之前使用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")));
    }
}