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


当前回答

在JavaFX的标题栏中插入自己的图标的另一种简单方法是使用以下方法将图像添加到你的主阶段:

Image ico = new Image("resources/images/iconLogo.png");
stage.getIcons().add(ico);

确保你导入javafx.scene.image.Image(如果使用netbeans这样的ide,这应该会自动为你完成)。

其他回答

我试过了,效果不错:

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

如果运行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(“image path”) );

在运行时切换图标:

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

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

如果你得到无效的URL或资源没有找到,把你的图标.png在“bin”文件夹在你的工作空间。