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.