skip to Main Content

I’m working on a Java game and my main issue is putting more than one component on a Jframe at once. Before you all yell at me, I HAVE done what was suggested in terms of layout managers and component sizes.

I finally realized my issue. I’m asking the complete wrong question. My main question is really this:

How do I allow two components to be visible in the same area at the same time in a JFrame? According to some people I asked, it’s impossible, hence the layout managers. But is there anyway to get around this? Perhaps using something like layers in Photoshop? I know there’s a Z-Index in HTML. Is there one in Java?

Thanks guys!

Sorry for my bad questions before 🙁 I appreciate all help that was given, especially by Camickr.

PS: I hope I structed this question right :s

Ab

3

Answers


  1. Take a look at JLayeredPane, its a container that allows layering: http://docs.oracle.com/javase/7/docs/api/javax/swing/JLayeredPane.html

    Login or Signup to reply.
  2. If you’re making a Java game, you should use a Canvas to draw all components. You can override the Canvas’ paint(Graphics) method, and loop over all components you want to draw there. Then you can easily draw two components on top of each other (the top component is the one drawn later in the loop).

    See the JavaDoc for Canvas

    Login or Signup to reply.
  3. How do I allow two components to be visible in the same area at the same time in a JFrame?

    You can still use layout managers. How do you think a GUI is built? There is always a hierarchy of components. Each parent component has a child component.

    JLabel child = new JLabel("Child Label");
    JPanel parent = new JPanel();
    parent.add( child );
    frame.add( parent );
    

    Now you have a hierarchy of frame -> content pane -> parent -> child. Depending on the layout managers you use at each level you can achieve different effects.

    You can always use a BorderLayout on each component to that the component you add to it will take up all the space. Of course when you start adding panels on top of one another you need to use setOpaque(false) so all the components can be seen.

    The key point from your other 4 postings is that unless your components have a preferred size, the layout can’t lay out the components properly.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search