I think you are using the JButton
wrong, the setIcon
and setPressedIcon
is literally for an icon next to the JButton
, however, for a game you probably want the background to change when pressed from one image to another, which by default the JButton
class does not support.
Here is a custom JButton
I made that allows exactly this:

CustomJButton.java:
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.JButton;
public class CustomJButton extends JButton {
private final BufferedImage normalIcon;
private final BufferedImage selectedIcon;
public CustomJButton(BufferedImage normalImage, BufferedImage selectedImage) {
super();
setOpaque(false);
setContentAreaFilled(false);
setBorder(null);
setFocusPainted(false);
setMargin(new Insets(0, 0, 0, 0));
this.normalIcon = normalImage;
this.selectedIcon = selectedImage;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(normalIcon.getWidth(), normalIcon.getHeight());
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// lets anti-alias for better quality
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// lets anti-alias for text too
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
// lets draw the correct image depending on if the button is pressed or not
if (getModel().isPressed()) {
g2d.drawImage(selectedIcon, 0, 0, getWidth(), getHeight(), this);
} else {
g2d.drawImage(normalIcon, 0, 0, getWidth(), getHeight(), this);
}
// calc string x and y position
Font font = getFont();
String text = getText();
FontMetrics metrics = g2d.getFontMetrics(font);
int textWidth = metrics.stringWidth(text);
int textHeight = metrics.getHeight();
int textY = getWidth() / 2 - textWidth / 2;
int textX = getHeight() / 2 - textHeight / 2 + metrics.getAscent();
// draw the text
g2d.drawString(text, textY, textX);
}
}
Which you would then use like this:
CustomJButton button = new CustomJButton(ImageIO.read(new URL("https://i.stack.imgur.com/xCGQQ.png")), ImageIO.read(new URL("https://i.stack.imgur.com/R9i1s.png")));
button.setFont(new Font("Jokerman", Font.BOLD, 22));
button.setForeground(Color.WHITE);
button.setText("Press Me!");
button.addActionListener((ActionEvent e) -> {
JOptionPane.showMessageDialog(frame, "You pressed me");
});