3

My first intention was to set TextInputDialog icon. But I started from setting stage icon. I saw couple SO questions with marvelous answers containing usually 2 lines of code.

First I tried to put this icon to /resources/icons but exception "Invalid URL or resource not found" appeared. To be sure I don't make any mistake writing file path I moved this icon to /source/sample directory. I use code (I will post whole code):

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

Everywhere it looks so simple to set icon. I also tried .jpg. not using file: throws exception, using file: compiles but I see no effect of changed icon. What am I doing wrong or where is the problem?

Urle
  • 131
  • 10
  • 1
    The string must contain the full path to the resource. If there's no scheme then the path is considered relative to the root of the classpath. When the image is under "icons/icon.png" you should be able to use `new Image("icons/icon.png")`. Prepend the path with "resources/" if that is a package instead of a root. – Slaw Mar 19 '19 at 14:17

1 Answers1

1

I've successfully used this to set an icon before

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

In my case, the application fxml file and AppIcon.png are in the same directory.

If you dont want to go that route, i would suggest trying

 Image image = new Image("file:./icon.png");

But that's a guess.

andrew-g-za
  • 967
  • 8
  • 13
  • First solution works. Second one doesn't, unfortunately. – Urle Mar 19 '19 at 12:58
  • https://stackoverflow.com/questions/10121991/javafx-application-icon "if it's wrapped in a containing jar you'll need to use the following approach instead:" `stage.getIcons().add(new Image(.class.getResourceAsStream("icon.png")));` but I just pasted this icon into src file from another directory. – Urle Mar 19 '19 at 13:06