Set Icon on Stage in JavaFX

2019-04-23 14:45发布

I wanted to know how should I set icons on javaFX stage. I have found this method, but it did not work properly.

  stage.getIcons().add(new Image(iconImagePath));

stage is an instance of javafx.stage.Stage, and I have imported javafx.scene.image.Image. This is the exception which we receive:

Invalid URL: Invalid URL or resource not found

Also, there is nothing wrong with the iconImagePath, its value is "G:/test.jpg" and there is a jpg file in the G drive named test. In addition, when we use ImageIO to read the same URL we can do it easily.

11条回答
爷、活的狠高调
2楼-- · 2019-04-23 15:25

This is what I've done and it work. The image is located in the root of my resource folder.

stage.getIcons().add(new Image("/ubuntu-mini.png"));

I am using JavaFX 8

查看更多
仙女界的扛把子
3楼-- · 2019-04-23 15:29

Here is the working code, which is exactly what you neened:

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 *
 * @author Manikant gautam
 * This is a beginner's sample application
 * using JAVAFX
 * 
*/

public class Helloworld extends Application {

    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });

        StackPane root = new StackPane();
        root.getChildren().add(btn);

        Scene scene = new Scene(root, 300, 250);
        // Set Icon From Here.
        primaryStage.getIcons().add(
            new Image("/resource/graphics/app_logo.png"));
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }


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

Set Icon by statement:

primaryStage.getIcons().add(new Image("/resource/graphics/app_logo.png"));
查看更多
劫难
4楼-- · 2019-04-23 15:33

Best Way:

stage.getIcons().add(new Image(getClass().getResource(IconImagePath).toExternalForm()));
查看更多
5楼-- · 2019-04-23 15:35
// Set the icon
stage.getIcons().add(new Image(getClass().getResourceAsStream("penguin.png")));

I faced the same problem. I used Netbeans. I'm not sure if the folder structure is different for other IDEs, but I had to put the picture in /build/classes/(package that contains the JavaFX class file). This means it doesn't go into the src folder.

查看更多
做个烂人
6楼-- · 2019-04-23 15:44

use

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

and put the image logo.png in root of your project ( at same directory where src )

查看更多
登录 后发表回答