Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Cannot apply background color to JPanel

843807Dec 11 2009 — edited Dec 11 2009
Hi,

I am using this code which I found on the internet in order to draw an image on a JPanel. But setBackground() does not work.
public class ImagePanel extends JPanel {
	private Image img;

	public ImagePanel(String img) {
		this(new ImageIcon(img).getImage());
	}

	public ImagePanel(Image img) {
		this.img = img;
		Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
		setPreferredSize(size);
		setMinimumSize(size);
		setMaximumSize(size);
		setSize(size);
		setOpaque(false);
		setBackground(Color.white);
		setForeground(Color.white);
		setLayout(new FlowLayout(FlowLayout.CENTER));
	}

	public void paintComponent(Graphics g) {
		g.drawImage(img, getWidth()/2-img.getWidth(null)/2, getHeight()/2-img.getHeight(null)/2, null);
		
	}

}
The problem is that I can't have the background or the foreground colored. My image has a white border around it, and I would like to paint my panel with the same color. Why I can't. What am I doing wrong?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 8 2010
Added on Dec 11 2009
4 comments
233 views