How to Change the icon on the title bar of a stage in java fx 2.0 of my application [duplicate]

别等时光非礼了梦想. 提交于 2019-11-29 03:41:51

Full program for starters :) This program set Stack Overflow Icon.

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

Output Screnshot

Updated for JavaFX 8

No need to change the code. It still works fine. Tested and verified in Java 1.8(1.8.0_45). Path can be set to local or remote both are supported.

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

OR

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

Hope it helps. Thanks!!

You can load the image from the classpath like this:

new Image(XYZ.class.getResourceAsStream("/xyz.png"))

where XYZ is some classname (maybe the one you're loading the image from) and xyz.png is the name of your image file, put in a directory (or JAR file) included in your classpath.

If you like to put the image next to the source file, you have to omit the / character. Your IDE needs to be configured to copy ressources (like *.png) from src to bin directory, then. But this is supposed to be the standard behaviour.

Does your image have correct size? Javadoc states:

public final ObservableList getIcons()

Gets the icon images to be used in the window decorations and when minimized. The images should be different sizes of the same image and the best size will be chosen, eg. 16x16, 32,32.

The solution i found by setting the properties of standalone working directory to package where my main and image is placed.

daviek19

Dont forget to do the import

import javafx.scene.image.Image;

Image icon = new Image(getClass().getResourceAsStream("myicon.png"));
stage.getIcons().add(icon);

Replace "myicon.png" with your icon. In this case it's in the same folder as your java class.

For those who had a problem with:

Invalid URL: Invalid URL or resource not found

The best solution is to make new package i.e image.icons and move there your .png image. Then you just need to write:

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

I hope this helps somebody!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!