Home Java Java-tips GUI Components 20buttons Buttons with Icons

Ask Questions?

View Latest Questions

Advertisement


 
 

Buttons with Icons
Posted on: July 22, 2006 at 12:00 AM
You can create buttons that show text, icons (images), or both.

Java: Buttons with Icons

You can create buttons that show text, icons (images), or both.

 

In this example you will learn how to create Buttons with Icons on it.

 

Different images can be associated with different button states and user interactions with the button (disabled, rollover, ...).

 

The two supported image formats are GIF and JPEG, although support for more image types is being worked on.

See Images - ImageIcon for an explanation of how to use ImageIcons for buttons.

 

To create a button with an icon

 

JButton next = new JButton(new ImageIcon("right.gif"));

or

JButton next = new JButton("Next", rightArrow);

Methods to change the icon on a JButton

It is common to show different icons when the button is disabled, the mouse is over it (rollover), etc. Java recognizes seven (7) different states for a button, and you can set a different image for each state.

Java computes two button images automatically: the disabled image is computed from the normal image, and the selected, disabled image is computed from the selected image if one is supplied.

Rollover image changes are not automatic -- first you must call b.setRolloverEnabled(true);.

   JButton b = new JButton(Icon x); // Create button with normal icon
   b.setIcon(Icon x);
   b.setDisabledIcon(Icon x);
   b.setPressedIcon(Icon x);
   b.setSelectedIcon(Icon x);
   b.setDisabledSelectedIcon(Icon x);
   
   b.setRolloverEnabled(boolean b); // turn on before rollovers work
   b.setRolloverIcon(Icon x);
   b.setRolloverSelectedIcon(Icon x);
   
Copyleft 2005 Fred Swartz MIT License
Advertisement


DMCA.com