Sunday, June 10, 2012

JavaFX 2: Transparent Stage

In this tutorial I am going to create a transparent Stage (window) with JavaFX 2, this means that the application won't have a window around the image.  In order to make Stage transparent we need to set StageStyle.TRANSPARENT. Also, I wanted here to add little close image, because I want to allow user to close application. Below you can take a look how our application will look in the end.

 You can use any image that you like for background, but I used this one: Background Image, and here you can download "close" image.



Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. import javafx.application.Application;
  2. import javafx.event.EventHandler;
  3. import javafx.scene.Scene;
  4. import javafx.scene.image.Image;
  5. import javafx.scene.image.ImageView;
  6. import javafx.scene.input.MouseEvent;
  7. import javafx.scene.layout.Pane;
  8. import javafx.stage.Stage;
  9. import javafx.stage.StageStyle;
  10.  
  11. public class TransparentStageMain extends Application {
  12.  
  13.     @Override
  14.     public void start(Stage stage) {
  15.         stage.initStyle(StageStyle.TRANSPARENT);
  16.  
  17.         Pane root = new Pane();
  18.  
  19.         Image img = new Image("javafx_big.jpg");
  20.         ImageView imgView = new ImageView(img);
  21.  
  22.         Image imgClose = new Image("close.png");
  23.         ImageView imgView1 = new ImageView(imgClose);
  24.         imgView1.setX(565);
  25.  
  26.         imgView1.setOnMouseClicked(new EventHandler<MouseEvent>() {
  27.             @Override
  28.             public void handle(MouseEvent arg0) {
  29.                 System.exit(0);
  30.             }
  31.         });
  32.  
  33.         root.getChildren().addAll(imgView, imgView1);
  34.  
  35.         final Scene scene = new Scene(root);
  36.         stage.setScene(scene);
  37.         stage.show();
  38.     }
  39.  
  40.     public static void main(String[] args) {
  41.         launch(args);
  42.     }
  43. }

4 comments:

  1. Good work , there is not much resource on Java FX. keep it going

    Thanks
    Javin
    20 design pattern interview questions

    ReplyDelete
  2. Thanks for sharing my article. :) I am glad that you like it. Feel free to to read and share also other articles on my blog.

    ReplyDelete
  3. No problem, thank you for leaving a comment.

    ReplyDelete
  4. nice tutorial, but do you know how to drag and minimize the window?

    ReplyDelete