0

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
michj36
  • 53
  • 7
  • You could make your character's component not opaque with [`JComponent#setOpaque`](https://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#setOpaque(boolean)) method. So it will allow the background to be visible. I recently did this (not with a game but you can get the idea from [this answer](http://stackoverflow.com/questions/37731882/background-image-hidding-the-other-components-like-buttons-labels-and-other-and/37734980#37734980)) – Frakcool Jun 14 '16 at 15:58
  • 1
    Also have a look at `JLayeredPane`, useful for third dimension positioning : https://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html – Arnaud Jun 14 '16 at 16:00
  • 1
    *"One would be a background board, the another - a player character."* It sounds like the entire game field plus character(s) would be best drawn in a single custom `JPanel`.. – Andrew Thompson Jun 14 '16 at 16:43

1 Answers1

1

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.

Max K
  • 656
  • 1
  • 6
  • 22