Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CardLayouts: How can I tell which card is visible?

Tags:

java

swing

I've been looking through the documentation for the Swing CardLayout and there doesn't appear to be any way to determine which card is currently showing baked in to the class. Yet there must be a way to ask the layout which card it is currently showing, right?

Due to project constraints, I can't simply extend it and add this functionality to a sub-class, so if there isn't such a function does that mean I'm stuck tracking the component's state external to the component (yuck!), or is there some other option buried somewhere deep in Swing?

like image 619
Tom Tresansky Avatar asked Aug 16 '11 13:08

Tom Tresansky


1 Answers

According to the How to Use CardLayout tutorial,

Conceptually, each component that a CardLayout manages is like a playing card or trading card in a stack, where only the top card is visible at any time. You can choose the card that is showing in any of the following ways:

  • By asking for either the first or last card, in the order it was added to the container
  • By flipping through the deck backwards or forwards
  • By specifying a card with a specific name

Try,

Component visibleComponent = foo.getComponent(0);

where foo is the JPanel instance using CardLayout.

Reference:

  • How to get the top card in Java's CardLayout
like image 78
mre Avatar answered Nov 08 '22 08:11

mre