Creating Buttons With a Rollover Effect

In GUIs, you can often see buttons that change their appearance when you hover over them with a mouse cursor. A button of this kind looks like an icon. When you hover over the button with a mouse cursor, a border appears around the button, and an icon or a background color changes, as just two examples. To create such buttons in JavaFX Script, it is convenient to use the Node.hover instance variable:

Source Code
var c = Circle {
    centerX: 80 centerY: 50 radius: 36
    fill: Color.LIGHTGREEN
    stroke: Color.DARKGREEN
    strokeWidth: 2
    opacity: bind if (c.hover) then 1 else 0
}

Initially, this button is completely transparent. When you hover over the button with a mouse cursor, the value of the hover variable becomes true and the button changes.

But what if you do not want to highlight the background? An obvious solution is to replace the third line in the previous code example with the following line:

Source Code
fill: null

But this solution does not work. The button is no longer highlighted at all. The reason is that unfilled areas do not receive mouse events. Therefore, the hover variable remains false even if the mouse cursor is over the button.

To solve the problem, apply a two-layer construction. Enable the upper layer of the "sandwich" to be absolutely transparent and receive mouse events. The bottom layer consists of a border and becomes visible in response to the change of the upper layer's hover variable. Note that in the following example the bottom layer is defined first and the upper layer is next.

Source Code
var c: Circle;
Circle {
   centerX: 200 centerY: 50 radius: 36
   fill: null
   stroke: Color.DARKRED
   strokeWidth: 2
   visible: bind c.hover
},
c = Circle {
   centerX: 200 centerY: 50 radius: 36
   opacity: 0
};

Now insert an icon between the layers and you have the finished button.

Explore both buttons in action:

You can find the complete code in Rollover.fx.

Rate This Article
Discussion

We welcome your participation in our community. Please keep your comments civil and on point. You may optionally provide your email address to be notified of replies—your information is not used for any other purpose. By submitting a comment, you agree to these Terms of Use.

 

English
日本語
한국어
简体中文
русский
Português do Brasil