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!

Weird transparency problem

843806Apr 7 2008 — edited Apr 8 2008
So, I realize that there are already a million threads out there with transparency. I've looked at some of them, and they haven't solved my problem.

Basically, what I'm trying to do is draw a grid over a background. I did this by creating a class that extends JPanel, and whose paintComponent() method draws a rectangle around it's edges.

Then I created another class that extends JFrame that adds 49 squares (the previous class) to a gridLayout to make a grid, and whose paintcomponent paints a background image.

Here's the code of the Squares:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JPanel;

public class Square extends JPanel {

	public Square() {
		setOpaque(false);
	}

	public void paintComponent(Graphics g) {
		Graphics2D g2 = (Graphics2D) g;
		g2.setColor(Color.BLUE);
                        //draw a 2 pixel line around the edge
		g2.drawRect(0, 0, getWidth(), getHeight());
		g2.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
	}
}
And here's the code for the JFrame:
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import javax.swing.JFrame;


public class board extends JFrame{
	
	Image background;
	public board(){
		background = ResourceRetriever.getImage("background.jpg");
		setLayout(new GridLayout(7,7,0,0));
		for(int i = 0; i<49; i++){
			add(new Square());
		}
		setSize(480,640);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		validate();
		setVisible(true);
	}
	
	public void paint(Graphics g){
		g.drawImage(background,0,0,getWidth(),getHeight(),null);
		super.paint(g);
		
	}
	public static void main(String[] args) {
		board larry = new board();
	}
}
When I run it, I get a 7*7 blue grid, just like I wanted to, but the background image doesn't come through. When I resize the frame, I get a faint flickering of the background image, but it quickly dissapears.

Any ideas? I've tried setting the background colors to transparent and fooling around with setOpaque() calls. I've also messed around with the timing of the super.paint() and super.paintComponent() calls as well.

I'm stumped
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 6 2008
Added on Apr 7 2008
2 comments
286 views