Java: Buttons with Icons

You can create buttons that show text, icons (images), or both. 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 of the button states.

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);