设置舞台图标

3

我的第一个想法是设置TextInputDialog图标。但我从设置舞台图标开始。我看到了一些SO问题,其中包含了令人惊叹的答案,通常只包含两行代码。

首先,我尝试将此图标放置在/resources/icons中,但出现了异常"无效的URL或未找到资源"。为了确保我不写错文件路径,我将此图标移动到/source/sample目录中。我使用以下代码(我将发布整个代码):

public void start(Stage stage) throws Exception {

    FXMLLoader loaderModyfikacjaKonfiguracji = new FXMLLoader(getClass().getResource("FXMLModyfikacjaKonfiguracji.fxml"));
    Parent root = loaderModyfikacjaKonfiguracji.load();
    stage.setTitle("Modyfikacja konfiguracji");
    Image image = new Image("file:icon.png");
    //stage.getIcons().removeAll();
    stage.getIcons().add(image);

    ControllerModyfikacjaKonfiguracji controllerModyfikacjaKonfiguracji = loaderModyfikacjaKonfiguracji.getController();

    stage.setScene(new Scene(root, 510, 700));
    stage.show();
}

在所有地方,设置图标看起来都很简单。我也尝试了 .jpg 格式。不使用 file: 会抛出异常,使用 file: 编译通过但是我没有看到更改后的图标效果。我做错了什么或者问题出在哪里?


1
字符串必须包含资源的完整路径。如果没有方案,则认为该路径相对于类路径的根目录。当图像位于“icons/icon.png”下时,您应该能够使用new Image("icons/icon.png")。如果这是一个包而不是根,请在路径前加上“resources/”。 - Slaw
1个回答

1

我以前成功地使用过这个来设置图标

primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("AppIcon.png")));

在我的情况下,应用程序 fxml 文件和 AppIcon.png 位于同一目录中。
如果您不想采用这种方法,我建议尝试。
 Image image = new Image("file:./icon.png");

但这只是一个猜测。

第一种解决方案可行。不幸的是,第二种方案不行。 - Urle
如果它被包含在一个jar文件中,你需要使用以下方法:stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("icon.png")));但是我只是将这个图标从另一个目录复制到了src文件中。 - Urle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接