That’s what I use for my game. It’s a JButton with rollover effect. Just pass in the 3 images (normal, selected, rollover) for the three states of the button. Checkout my game to find out how it looks/behaves. All buttons in the game use this class.
import java.awt.FontMetrics;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import javax.swing.JButton;
/**
* Represents a nice looking button with rollover effect. Pass in the 3 images for the different
* states of the button.
*
* @author king
* @since March 8, 2005
*/
public class FancyButton extends JButton {
/** Image for normal state. */
private Image normalImage;
/** Image for rollover state. */
private Image rolloverImage;
/** Image for selected state. */
private Image selectedImage;
/**
* Constructor for the button.
*
* @param normalImage The image for the normal state.
* @param rolloverImage The image for the rollover state.
* @param selectedImage The image for the selected state.
*/
public FancyButton(Image normalImage, Image rolloverImage, Image selectedImage) {
this.normalImage = normalImage;
this.rolloverImage = rolloverImage;
this.selectedImage = selectedImage;
// set transparent
setOpaque(false);
setBorderPainted(false);
// set text color
setForeground(NORMAL_TEXT_COLOR);
// set the size based on image
Dimension size = new Dimension(normalImage.getWidth(this), normalImage.getHeight(this));
setSize(size);
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
// Enable rollover
setRolloverEnabled(true);
}
/**
* Draws this component.
*
* @param g Graphics context.
*/
public void paintComponent(Graphics g) {
// highlight depending on rollover or button pressed
if (model.isPressed() || isSelected()) {
g.drawImage(this.selectedImage, 0, 0, this);
}
else if (model.isRollover()) {
g.drawImage(this.rolloverImage, 0, 0, this);
}
else {
g.drawImage(this.normalImage, 0, 0, this);
}
// Use antialiased text
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
if (getIcon() != null) {
int width = getSize().width;
int height = getSize().height;
int iconWidth = getIcon().getIconWidth();
int iconHeight = getIcon().getIconHeight();
getIcon().paintIcon(this, g, (width - iconWidth) / 2, (height - iconHeight) / 2);
}
else {
// Draw the button text
int width = getSize().width;
int height = getSize().height;
FontMetrics metrics = g.getFontMetrics();
int fontHeight = metrics.getHeight();
int fontWidth = metrics.stringWidth(getText());
int x = (width - fontWidth) / 2;
int y = (height + fontHeight) / 2 - 3;
if (isEnabled()) {
g.setColor(getForeground());
}
else {
g.setColor(DISABLED_TEXT_COLOR);
}
g.drawString(getText(), x, y);
}
}
}