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


当前回答

假设你的stage是“stage”,文件在文件系统上:

stage.getIcons().add(new Image("file:icon.png"));

根据下面的评论,如果它被包装在一个容器中,你将需要使用以下方法:

stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("icon.png")));

其他回答

假设你的stage是“stage”,文件在文件系统上:

stage.getIcons().add(new Image("file:icon.png"));

根据下面的评论,如果它被包装在一个容器中,你将需要使用以下方法:

stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("icon.png")));

这个程序为StackOverflowIcon设置图标。

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class StackoverflowIcon extends Application {

    @Override
    public void start(Stage stage) {
        StackPane root = new StackPane();
        // set icon
        stage.getIcons().add(new Image("/path/to/stackoverflow.jpg"));
        stage.setTitle("Wow!! Stackoverflow Icon");
        stage.setScene(new Scene(root, 300, 250));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

输出Screnshot

为JavaFX 8更新

不需要更改代码。它仍然可以正常工作。在Java 1.8(1.8.0_45)中测试和验证。路径可设置为本地或远程均支持。

stage.getIcons().add(new Image("/path/to/javaicon.png"));

OR

stage.getIcons().add(new Image("https://example.com/javaicon.png"));

希望能有所帮助。谢谢! !

如果你有一个图像文件夹并且图标保存在其中,使用这个

stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("/images/comparison.png")));

如果你直接从你的包中使用它,这不是一个好的做法,使用这个

stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("comparison.png")));

如果你有一个文件夹结构里面有你的图标

stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("../images/comparison.png")));

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

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

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

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

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