How to add a Rollover and Pressed Icon to a JButton Component in Java?

Many times when we use button in User Interface , we need to have rollover or pressed effect for the button for various uses. Lets see how we can have rollover and pressed icon effect to the JButton which we create using the icon. Rollover effect mean changing the image behavior or properties when moving the mouse over the icon of the button. Pressed effect is when an image properties change when we mouse click on the button but do not release it.
So to get the rollover or pressed effect we can change the image or icon of the button on specific action i.e mouse over and mouse click. Java swing provides two methods setRolloverIcon and setProgressIcon which we can use to achieve both the effects.
Lets see what these two method do


This method is provided by JButton class. When we set the roll over icon to the button using this method then when we mouse over the button, the image icon which we are sending gets set. This method accepts image icon as an argument.


When we set the icon using this method , once we click this image icon gets displayed. This method also requires image icon as an argument.

Now lets see how we can use it using programming, following is a code snippet which shows the rollover and pressed icon effect.

JPanel p = new JPanel();
effectTest.add( p ,BorderLayout.CENTER );
JButton buttonTest = new JButton( new ImageIcon( "button.gif" ) );
panel.add( buttonTest );
ImageIcon rolloverIcon = new ImageIcon( "rollover_button.gif" );
buttonTest.setRolloverIcon( rolloverIcon ); // Setting image when mouse rollover happens
ImageIcon pressedIcon = new ImageIcon( "pressed_button.gif" );
buttonTest.setPressedIcon( pressedIcon ); // Setting image when mouse click happens

In above program as we can see , we have created JButton with imageicon. We have two more images which we want to use it when rollover and mouse click happens. For this purpose we have set the icons using setRolloverIcon and setPressedIcon methods.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment


Post a Comment