Reputation: 95
How can i set the background of JComponent ? I currently have this class :
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JComponent;
public class ImagePanel extends JComponent {
/**
*
*/
private static final long serialVersionUID = 1L;
private Image image;
public ImagePanel(Image image) {
this.setLayout(new BorderLayout());
this.image = image;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
private BufferedImage myImage;
private JButton button = new JButton("Click");
try {
myImage = ImageIO.read(new File("/images/picture.png"));
} catch (IOException e) {
e.printStackTrace();
}
I used the following code to paint the JFrame's content pane, but i don't know how to do it for a JButton
Upvotes: 1
Views: 231
Reputation: 285403
The best way to display an image on a JButton is to create an ImageIcon with the button and then set the JButton's icon via setIcon(myIcon)
private BufferedImage myImage;
private JButton button = new JButton("Click");
public MyClass() {
try {
// much better to get the image as a resource
// NOT as a File
myImage = ImageIO.read(new File("/images/picture.png"));
Icon buttonIcon = new ImageIcon(myImage);
button.setIcon(buttonIcon);
} catch (IOException e) {
e.printStackTrace();
}
}
You state:
This doesn't set it as background. It just create an icon next to the text
Then you have several options:
Upvotes: 2