Building an Image-Based Rollover Button

By Josh Marinacci, September 22, 2008

JavaFX has a built in SwingButton class based on Swing's JButton class, but do not feel limited by this class. It's very easy to create your own button that has any effect you can imagine. This example will show you how to create a button with a rollover effect using only images.

Understanding the Code

The following code creates a close button.

Source Code
public class CloseButton extends CustomNode {
    var image:Image;
    var images:Image[];
    public var onClicked:function():Void;

    init {
        images = [
            Image { url: "{__DIR__}resources/close_normal.png" },
            Image { url: "{__DIR__}resources/close_hover.png" },
            Image { url: "{__DIR__}resources/close_pressed.png" },
        ];
        image = images[0];
    }

    override public function create():Node {
        return ImageView {
            image: bind image
            onMouseEntered:  function(e:MouseEvent) { image = images[1] }
            onMouseExited:   function(e:MouseEvent) { image = images[0] }
            onMousePressed:  function(e:MouseEvent) { image = images[2] }
            onMouseReleased: function(e:MouseEvent) {
                image = images[0];
                if(onClicked != null) {
                    onClicked();
                }
            }
        }
    }

}

The CloseButton.fx class

The image button works by preloading all of the images and then switching the current image based on mouse events.

To use this class just place it in a stage and assign a delegate function to the onClicked variable.

Source Code
var stage:Stage = Stage {
    scene: Scene {
        content: CloseButton {
            onClicked: function():Void {
                stage.close();
            }
        }
    }
}