Java: using an image as a button
I would like to use an image as a button in Java, and I tried to do this:
BufferedImage buttonIcon = ImageIO.read(new File("buttonIconPath"));
button = new JButton(new ImageIcon(buttonIcon));
But this still shows the actual button behind the image, I would only like the image to function as the button, how can I do this?
Remove the border like so:
button.setBorder(BorderFactory.createEmptyBorder());
and then also the contents1:
button.setContentAreaFilled(false);
1: Taken from the solution added to the question by @3sdmx
A suggestion would be to set the Image as a label and add a mouse listener to the label to detect clicks.
Example:
ImageIcon icon = ...;
JLabel button = new JLabel(icon);
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
... handle the click ...
}
});
buttonIcon.setBorder(new EmptyBorder(0,0,0,0));
button.setBorderPainted( false );