简体   繁体   中英

Java - Swing - displaying multiple JComponents in one JFrame

in a game, I would like to display simultaneously two JComponent instances in a JFrame . One would be a background board, the another - a player character.

So, one component (a background) would be behind another (a character). The character would be drawn of several rectangles and thus it will most commonly have some wholly transparent area.

How to do that? I know that normally, when I add two components to a frame (method add(Component) ), only the last-added component is visible. This is done by following code:

frame.add(backg); // backg is an instance of a certain class that derives from JComponent
// (...)
frame.add(psc); // psc is an instance of an another class that derives from JComponent
frame.pack();
frame.setVisible(true);

How should I change the code above?

First of all, if you are looking to write a game in Java, try out Slick2D provides numerous tools and far better graphical capabilties (being wrapped around LWJGL which wraps around OpenGL). Secondly, if you do decide to go the Swing route, here's a simple solution:

    //Player + background components defined here
    playerComp.setOpaque(false);
    JLayeredPane layer = new JLayeredPane();
    layer.add(backgroundComp,1,0);
    layer.add(playerComp,2,0);

I believe that both these solutions were mentioned above in the comments. Setting the player component opaquity to false allows those transparent areas to show components behind the player, or the background image. If you're familiar with a z-index in CSS/HTML, a JLayeredPane basically adds a z-index to Swing by allowing you to set the order in which components are rendered. So, set the player to opaque, and then render it in front of the background component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM