Transparent JPanel, Canvas background in JFrame

Posted by Andy Tyurin on Game Development See other posts from Game Development or by Andy Tyurin
Published on 2014-08-20T14:38:30Z Indexed on 2014/08/20 16:37 UTC
Read the original article Hit count: 244

Filed under:

I wanna make canvas background and add some elements on top of it. For this goal I made JPanel as transparent container with setOpaque(false) and added it as first of JFrame container, then I added canvas with black background (in future I wanna set animation) to JFrame as second element.

But I can't undestand why i see grey background, not a black. Any suggestions?

public class Game extends JFrame {
    public Container container; //Game container with components
    public Canvas backgroundLayer; //Background layer of a game
    public JPanel elementsLayer; //elements panel (top of backgroundLayer), holds different elements

    private Dimension startGameDimension = new Dimension(800,600); //start game dimension

    public Game() {
        //init main window
        super("Astra LaserForces");
        setSize(startGameDimension);
        setBackground(Color.CYAN);
        container=getContentPane();
        container.setLayout(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //init jpanel elements layer
        elementsLayer=new JPanel();
        elementsLayer.setSize(startGameDimension);
        elementsLayer.setBackground(Color.BLUE);
        elementsLayer.setOpaque(false);
        container.add(elementsLayer);

        //init canvas background layer
        backgroundLayer = new Canvas();
        backgroundLayer.setSize(startGameDimension);
        backgroundLayer.setBackground(Color.BLACK); //set default black color
        container.add(backgroundLayer);

    }

    //start game
    public void start() {
        setVisible(true);

    }

    //create new instance of game and start it
    public static void main(String[] args) {
        new Game().start();
    }
}

enter image description here

© Game Development or respective owner

Related posts about java