Saturday, November 9, 2013

JavaFX example: how to set icon of application window

This example show how to set icon of application window, by calling:

Stage.getIcons().add(applicationIcon);

Also show how to set icon dynamically at run-time, when 'Hello World' button clicked.

set icon of application window
set icon of application window

package javafx_applicationicon;

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

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_ApplicationIcon extends Application {

    @Override
    public void start(final 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!");
                
                //load another image from internet
                //and dynamically add it as new apllication icon
                Image anotherIcon = new Image("http://goo.gl/kYEQl");
                primaryStage.getIcons().add(anotherIcon);
            }
        });
        
        StackPane root = new StackPane();
        root.getChildren().add(btn);
        
        Scene scene = new Scene(root, 300, 250);
        
        //set icon of the application
        Image applicationIcon = new Image(getClass().getResourceAsStream("dukes_36x36.png"));
        primaryStage.getIcons().add(applicationIcon);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

No comments:

Post a Comment

Post a Comment