0

I am having trouble getting two different components to display at the same time.

public class BandViewer
{
   public static void main(String[] args)
   {
      JFrame frame = new JFrame();
      frame.setSize(1000, 800);
      frame.setTitle("band");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      BandComponent component = new BandComponent();
      ConcertBackground component1 = new ConcertBackground();
      frame.add(component);
      frame.add(component1);

      frame.setVisible(true);
   }
}

Now I read on this forum that you can do something to display both at the same time but wasn't able to figure out how it was done. Can anyone please help? I want to have one to be in front of the other. Is their some way to control the layering? Thanks in advance.

mKorbel
  • 109,525
  • 20
  • 134
  • 319

2 Answers2

1

Within a JFrame a Layout Manager is usually used to position different components, tutorial here.

Something like:

Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());

To set up a a basic layout manager for your JFrame. There is also a JLayeredPane which allows you to specify a z-order - docs page, so something like:

JLayeredPane layeredPane = new JLayeredPane();

BandComponent component = new BandComponent();
ConcertBackground component1 = new ConcertBackground();
layeredPane.add(component, 0); // 0 to display underneath component1
layeredPane.add(component1, 1);

contentPane.add(layeredPane);

A display hierachy is set up in this manner, with objects within objects. I'm not sure what BandComponent and ConcertBackground classes are, but if they inherit from Swing classes you might have to set a preferred size or similar to ensure they don't have a zero size!

Henry Florence
  • 2,848
  • 19
  • 16
1

The problem you are having is because JFrame by default uses a BorderLayout. BorderLayout only allows a single component to appear in any one of it's five available positions.

To add multiple components to a single container, you need to configure the layout or use one which better meets your needs...

Take a look at A Visual Guide to Layout Managers for more examples

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366