PDA

View Full Version : How to change the alpha of a JPanel?



nickcherryjiggz
April 21st, 2007, 01:39 PM
I'm pretty new to Java, so sorry if this is a dumb question. I'm trying to make a JPanel semi-transparent. I have the class playPanel.java...



import java.awt.*;
import javax.swing.*;

public class playPanel extends JPanel
{
int blockType;
public playPanel()
{
super();
setLayout(null);
}
}...and from another class, gameFrame.java, I create a new playPanel...


pp = new playPanel();
pp.setBounds((int)(appWidth * .5 - playWidth * .5), (int)(appHeight * .5 - playHeight * .55 - 10), playWidth, playHeight);
getContentPane().add(pp);Is there an easy way to change the alpha of pp?

Voetsjoeba
April 21st, 2007, 01:43 PM
You could try setOpaque(false), and then overwrite paintComponent to manually draw the background rectangle using a custom transparent Color object.

nickcherryjiggz
April 21st, 2007, 02:24 PM
Thanks a lot Voetsjoeba...here are the updated files in case anyone else might run into a similar problem...


import java.awt.*;
import javax.swing.*;

public class playPanel extends JPanel
{
int blockType;
public playPanel()
{
super();
setLayout(null);
}

public void paintComponent(Graphics g)
{
super.paintComponent(g);
Color ppColor = new Color(255, 10, 250, 70); //r,g,b,alpha
g.setColor(ppColor);
g.fillRect(0,0,260,500); //x,y,width,height
}
}and then to gameFrame.java...

pp = new playPanel();
pp.setBounds((int)(appWidth * .5 - playWidth * .5), (int)(appHeight * .5 - playHeight * .55 - 10), playWidth, playHeight);
getContentPane().add(pp);
pp.setOpaque(false);