Java – check if there is a card with name in CardLayout
I have a CardLayout. I only add cards as needed Therefore, when I need to display a specific card (identified by its name), I need a way to check whether a card with that name already exists so that I can display or create it accordingly
According to CardLayout documentation
Therefore, if I ask it to display cards that have not been added, no error will be thrown I can't find any API that allows me to check if the card exists
So, is that possible? If not, how to solve this problem? There is a solution that I manually remember what cards I added, but I feel that swing should be able to handle this
Solution
The CardLayout API cannot check whether a component with the given name has been added
If you really want to do this (but I strongly recommend against), you can use reflection on the CardLayout used by the container, read its vector field, and then check the given name of each entry (type CardLayout $card) As you can see, this looks like a hacker. If one day CardLayout is refactored, it may break (the current implementation is very ugly)
The best way is to directly track the names of all added children in set < string > Somewhere Anyway, it's really not a big deal