2

Can one component (e.g. a JLabel) be in multiple cards using CardLayout?

Currently it seems that the component appears only at the last card it was added to.

If there is a way to do this, should I? Is it bad practice? Or is there some alternative?

durron597
  • 31,968
  • 17
  • 99
  • 158
Justas S
  • 584
  • 4
  • 12
  • 34
  • possible duplicate of [Can't a Swing component be added to multiple containers?](http://stackoverflow.com/questions/4620601/cant-a-swing-component-be-added-to-multiple-containers) – durron597 May 07 '14 at 14:12

1 Answers1

5

You are correct that it only appears in the "last card it was added to", but that has nothing to do with CardLayout, that has to do with the fact each component can only be in one parent.

From the Javadoc for java.awt.Container.addImpl(Component comp, Object constraints, int index):

If the component is not an ancestor of this container and has a non-null parent, it is removed from its current parent before it is added to this container.

durron597
  • 31,968
  • 17
  • 99
  • 158
  • Okay... I guess I could create a component for each container but I don't really see the point. The label is used for displaying errors. Or should I create one label for one card and then work out which one is used and display that one? – Justas S May 07 '14 at 14:08
  • 2
    @Bebras why not have the `errorLabel` be in the parent panel? – durron597 May 07 '14 at 14:09
  • You mean to add it to the same one which contains my cards? – Justas S May 07 '14 at 15:07
  • But won't it make it a card aswell? And where exactly will it appear? Because in different cards it's in different positions – Justas S May 07 '14 at 15:12
  • 2
    Sorry, I meant the parent container of the `CardLayout` formatted `JPanel`, and then it would appear next to the cards. But if you need it to be in different positions, I would use a separate `JLabel`, yes. – durron597 May 07 '14 at 15:16