0
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ What's the purpose of that JPanel? \$\endgroup\$
    – Thomas
    Aug 21, 2014 at 11:08
  • \$\begingroup\$ Main aim to create animated background thats you can change in future and jpanel as top container for top elements. For example i have background animation with stars and menu with buttons. When i click start game, my canvas will change animation and my jpanel destroy menu component. \$\endgroup\$
    – nrei
    Aug 22, 2014 at 6:31

1 Answer 1

0
\$\begingroup\$

Container.add doesn't stack components on top of each other -- it appends them according to the installed LayoutManager. Have a look at JLayeredPane instead to achieve the effect you're looking for.

But also consider just drawing everything in the Canvas directly (first the background, then the foreground) to avoid the whole Swing kitchen sink.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .