I have a CardLayout in which I add cards only as needed. So, when the need arises to show a particular card (identifed by its name), I need a way to check if a card with that name is already present, so that I can either show or create it accordingly.
According to the CardLayout documentation
Flips to the component that was added to this layout with the specified name, using addLayoutComponent. If no such component exists, then nothing happens.
So, no error will be thrown if I ask it to show a card that hasn't been added yet. I couldn't find any API that would let me check if a card is present.
So, is this possible to do? If not how would one go about addressing this? There is the solution that I manually remember what cards I have added but it feels swing should be able to handle this.
CardLayout API provides no way to check if a component has already been added with a given name.
If you really want to do that (but I would strongly advise AGAINST doing that), then you could use reflection on the CardLayout used by the container, and read its vector field, then check each entry (of type CardLayout$Card) for the given name. As you see, that looks like a hack and it could break if CardLayout was refactored some day (current implementation is quite ugly).
The best way would be for you to directly keep track of the names of all added children in a Set<String> field somewhere. And this is really not a big deal to do that anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With