JButton Rollover Image

JButton RollOver Icon
JButton RollOver Icon

1. About ImageIcon Class

In the Last Example on JButton with ImageIcon, we learned how to display the Image in a Java Swing’s JButton. Now, we will see how to use these image icons as roll-over images. When mouse enters the JButton, we can change the default image with a new one. We call this image a Roll-Over image and the image stays till mouse cursor rests on the JButton. Once the mouse cursor leaves the JButton, the default image will be displayed. We can also show a different image when user pressed the push button, and the image is called Pressed-Image.

2. About the Example

The below screen shows the JFrame Window, which we will create in this example:

JButton RollOver Icon
JButton RollOver Icon

In the above example, we have three Java Swing JButtons. All these buttons display a normal image when the JFrame displays. Each button will display three image icons based on the mouse action. The images for Normal, button pressed and mouse-enter are shown in the above screen. Let us proceed with the example and start coding.

3. Create JButton Rollover Image Icons

In the below code, we create three ImageIcon instances from the images living in the C:\Temp folder. You can create your own image or copy the images from the above screenshot using Paint Brush option, select & cut. We use these ImageIcons for the mouse actions.

4. Enable JButton Rollover

Now, we will create all three buttons. You can note that in the constructor, we do pass the ImageIcon instance. Before adding these JButtons to the JFrame window, we enable the roll-over behaviour via the method call setRolloverEnabled. Once we enable it, Swing will take care of tracking the mouse events and displaying the relevant ImageIcons.

5. Assign JButton Rollover Icons

The method setIcon method will set the default Icon for the button. When the mouse is not interacting with the JButton, Swing will display this image on the button. In our case, we set IconNormal instance to all three buttons. Method setRolloverIcon will set the Icon, which Swing will display when the mouse cursor enters the JButton component. Whereas the setPressedIcon will set the icon, which will display while user pressing the button and not released the mouse. So, to see this image, one should hold-down the mouse button. Also note when we do not specify an icon using the method setPressedIcon, swing will show the default icon/image which was set using the setIcon method.

You can watch how this example works in the below Youtube video.

6. JButton Rollover Images – Youtube Demo

7. Code Reference

7.1 MainEntry.java

7.2 JButtonRollOverExample.java

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: