Add a Rollover and Pressed Icon to a JButton Component in Java
Description
The following code shows how to add a Rollover and Pressed Icon to a JButton Component.
Example
// w w w. j a va 2 s. c o m
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main {
public static void main(String[] argv) throws Exception {
JFrame frame = new JFrame("DefaultButton");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton();
// Add rollover icon
Icon rolloverIcon = new ImageIcon("r.gif");
button.setRolloverIcon(rolloverIcon);
// Add pressed icon
Icon pressedIcon = new ImageIcon("p.gif");
button.setPressedIcon(pressedIcon);
// To remove rollover icon, set to null
button.setRolloverIcon(null);
// To remove pressed icon, set to null
button.setPressedIcon(null);
// Get gap size; default is 4
int gapSize = button.getIconTextGap();
// Set gap size
button.setIconTextGap(8);
frame.add(button);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »