I'm trying to add an overlay to an Applet, displayed in a JFrame.
The Applet is on the content pane, while the overlay is on the JLayeredPane of the JFrame.
Here's what it looks like visually
The only thing happening that isn't shown, is that the addApplet() method is called once the Applet has been loaded and is ready to play.
I tried to disable all drawing in the JLayeredPane, yet it still draws the grey background that is visible. I don't know where that background is coming from.
Note that both of the colors are visible, so each PaintComponent must be transparent.
How do I get rid of the grey background?
public class RuneFrame extends JFrame {
private JLabel loadingLabel;
private PaintComponent paintLayer1;
private PaintComponent paintLayer2;
public RuneFrame() {
super("Rune");
this.setSize(781, 542);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initUI();
}
private void initUI() {
loadingLabel = new JLabel("Loading...");
loadingLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(loadingLabel);
setLocationRelativeTo(null);
}
/**
* Adds an Applet to the frame. Do this when the applet has loaded.
* @param applet Game shown in this frame.
*/
public void addApplet(Applet applet) {
remove(loadingLabel);
paintLayer1 = new PaintComponent(Color.yellow, new Color(0,0,0,0));
this.getLayeredPane().add(paintLayer1, new Integer(1000));
paintLayer2 = new PaintComponent(new Color(0,0,0,0), Color.red);
this.getLayeredPane().add(paintLayer2, new Integer(1000));
this.getLayeredPane().setOpaque(false);
this.getLayeredPane().setBackground(new Color(0,0,0,0));
add(applet);
pack();
}
}
public class PaintComponent extends JComponent {
private Color c1;
private Color c2;
public PaintComponent(Color c1, Color c2) {
super();
this.c1 = c1;
this.c2 = c2;
this.setOpaque(false);
this.setSize(300, 300);
this.setBackground(new Color(0, 0, 0, 0));
}
@Override
public void paint(Graphics g) {
//super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
int w = 200;
int h = 200;
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, .5f));
g2.setPaint(new GradientPaint(0, 0, c1, 0, h, c2));
g2.fillRect(0, 0, w, h);
g2.dispose();
}
}
Applet
) aren't capable of been transparent/translucent. Thepaint
method of yourPaintComponent
should be callingsuper.paint
, assuming you're expecting it to paint it's childrenJLayeredPane
is used by theJFrame
Applet
wont be transparent. It's in the back. The idea is that the Applet is drawn first - then thePaintComponent
on top. That also explains why I'm not callingsuper.paint
: I'm not interested in anything else than the gradient. EDIT: I read the documentation onJRootPane
before posting. It says "You can choose to put components in the root pane's layered pane".Applet
, and paint my overlay using the applet's ownpaint()
.