Adding a Rollover and Pressed Icon to a JButton Component in Java

Here, you will learn about adding event i.e. the rollover and
click icon to a JButton
component of swing in java. Rollover means moving mouse pointer above the icon
on the button. This program shows an icon or image on the button
if the mouse pointer moves above the Button then your icon or image should be changed.
When you click on the button then another image or
icon should be shown on the button.
This program displays a button on a frame. Button shows
different icons like: cut, copy and paste on different
events. At first, the button shows the "cut" icon
and when the mouse pointer moves above the button then the button shows the
"copy" icon and when you click on the button then the "paste"
icon is seen. Following are the screenshot of the application:
This the "cut" image which occurs by default
when the program is rum from the command prompt.

This is the "copy" image which occurs by
default when user will rollover the image or button.

And this is the "paste" image which occurs by
default when user clicks on the button.

Code Description:
These events are managed by the program using some APIs
or methods as follows:
button.setRolloverIcon(Icon icon_name):
This is the method of the JButton class which
is used to set the icon or image to a button for display when the mouse pointer
rolls over the icon or the button. The icon or image is passed through the
method as a parameter.
button.setPressIcon(Icon press):
This is the method of the JButton class which
is used to set the icon or image to a object for displaying when the button is
clicked. The icon or image is specified in the method argument as a parameter.
Here is the code of program:
import javax.swing.*;
import java.awt.*;
public class RolloverComponent{
public static void main(String[] args) {
JFrame frame = new JFrame("Adding a Rollover and Pressed Icon
to a JButton Component");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel,BorderLayout.CENTER);
JButton cutbutton = new JButton(new ImageIcon("cut.gif"));
panel.add(cutbutton);
ImageIcon rollover = new ImageIcon("copy.gif");
cutbutton.setRolloverIcon(rollover);
ImageIcon press = new ImageIcon("paste.gif");
cutbutton.setPressedIcon(press);
frame.setSize(400,400);
frame.setVisible(true);
}
}
|
Download this example.

|
Current Comments
2 comments so far (post your own) View All Comments Latest 10 Comments:how do i change the label of JBUTTON to show up arrow
Posted by sumeet on Friday, 05.4.07 @ 15:28pm | #15262
Y isnt that the images arent working for me.i tried to specify an image of my choice and it wasnt working.wat is the pblm...?
Posted by pradeesh on Wednesday, 04.25.07 @ 16:02pm | #14913