Fading Transparent Window

By Josh Marinacci, September 24, 2008

This example shows you how to build a window which is transparent when the mouse cursor is outside of it, but fades in to be more opaque when the cursor moves inside.

Outside

Inside

Understanding the Code

This example has two main parts. First, it creates a Timeline called fade which makes the customOpacity variable go from 0.4 to 0.9. The toggle variable is set to true. This setting makes the direction of the animation reverse every time it is called.

Source Code
import javafx.animation.*;
import javafx.scene.*;
import javafx.scene.input.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.scene.text.*;
import javafx.stage.Stage;

var opacity = 0.5;
var fade = Timeline {
    keyFrames: [
        at(0s) { opacity => 0.4 tween Interpolator.LINEAR },
        at(0.5s) { opacity => 0.9 tween Interpolator.LINEAR },
    ]
};

Figure 1: Fade Animation

The second part of the code creates a Frame with its opacity bound to the customOpacity variable. The content of the frame is some text and an overlay rectangle with listeners for mouse events. Whenever the mouse cursor enters or exits the rectangle, it starts the fade animation. The toggle attribute on the fade animation makes the fade reverse each time fade.start() function is called.

Source Code
Stage {
    width: 400 height: 250
    opacity: bind opacity;
	title: "Transparent Window"
    scene: Scene {
        fill: Color.WHITE
        content: [
            Text { content: "Surrender Earthling!" 
                y: 150 x: 100 font: Font { size: 25 } },
            Rectangle {
                width: 400 height: 250
                fill: Color.rgb(0,0,0,0)
                onMouseEntered: function(e:MouseEvent) {
                    fade.rate = 1.0;
                    fade.play();
                }
                onMouseExited: function(e:MouseEvent) {
                    fade.rate = -1.0;
                    fade.play();
                }
            }
        ]
    }
};

Figure 2: Creating a Frame