Reputation: 786
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?
Upvotes: 58
Views: 105595
Reputation: 23629
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
Upvotes: 33
Reputation: 6614
I followed below steps and i could create an 'ImageButton' successfully.
JButton
info.png
icon in the src\main\resources folder and loaded using class loader). The project structure is as here. Border
PFB the code that worked for me
JButton btnNewButton = new JButton("");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Info clicked");
}
});
String iconfilePath = this.getClass().getClassLoader().getResource("info.png").getFile();
btnNewButton.setIcon(new ImageIcon(iconfilePath));
btnNewButton.setBounds(10, 438, 39, 31);
btnNewButton.setBorder(BorderFactory.createEmptyBorder());
btnNewButton.setContentAreaFilled(false);
btnNewButton.setFocusable(false);
contentPane.add(btnNewButton);
The output button resulted from above code is as below
Upvotes: 0
Reputation: 11
BufferedImage buttonIcon = ImageIO.read(new File("myImage.png"));
button = new JButton(new ImageIcon(buttonIcon));
button.setBorderPainted(false);
button.setFocusPainted(false);
button.setContentAreaFilled(false);
Upvotes: 1
Reputation: 331
This can be done easily in netbeans by setting the contentAreaFilled Property to False
Upvotes: 1
Reputation: 7450
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 ...
}
});
Upvotes: 9
Reputation: 751
As far i know, there is no easy way of doing it, you will need to override the "paintComponent" method of the JButton class to aint your image, if you only want to display an image and behave like a button, you can add a JPanel wich draws the image (clicky) and add a MouseListener/MouseAdapter to handle the "mousePressed" event
Upvotes: 0