title: How to get the top card in Java's CardLayout
body: <p>Is it possible to get the top card in Java's CardLayout?
  I've tried looping through each component to check for visibility with isVisible() but it seems that they're all "visible".</p>
  
  <p>Edit: By "top card" I mean the one that's currently at the "top", being displayed, not the first or last cards. Also, I don't know if it helps but I'm looking for a JPanel (or a subclass thereof)</p>
  
  <p>Edit: Code snippet  </p>
  
  <pre><code>for (Component component : getComponents()) {
   if (component instanceof JPanel &amp;&amp; component.isVisible()) {
    currentPanel = (JPanel) component;
    System.out.println(currentPanel.getClass().getName());
   }
  }  
  </code></pre>
  
  <p>The above code always prints out every component class's name, regardless if they are the visible card or not.</p>
  
  <p><strong>Edit</strong>: I'm using this as part of a school assignment. I'm not trying to get a freebie here, the assignment does not revolve around this layout. It just seems to be the most convenient layout for changing between panels. My teacher has specified that there is to be no third party code in the project. I've seen the implementation from camickr's link before but I can't use it. I can loosely implement similar features it and maybe give a reference it in the documentation but I can't simply download and use it.</p>
  
  <p><strong>Edit</strong>: The reason I'm trying to get the top card is because I have a toolbar with an "Add" button. Instead of having one add button for each of my two possible things I wanted it to know which to add simply by looking at what panel is currently being viewed. If there is another, more appropriate way to do this please let me know.</p>
  
  <p><strong>Edit</strong>: Thanks everyone for helping out. I figured out what the problem was. I guess it was my fault since I didn't provide enough detail. Two of my cards are <code>JScrollPane</code>s and I also needed to look through its contents to find out if one of those panels was the one I was seeing. I didn't check for <code>isVisible()</code> on the scroll pane itself, i had been looking at it's contends that are always visible, it was the scroll pane who's visibility I needed to verify.</p>
  
  <pre><code>public JPanel getCurrentPanel() {
          JPanel currentPanel = null;
  
          for (Component component : getComponents()) {
              if (component.isVisible()) {
                  if (component instanceof JPanel) 
                      currentPanel = (JPanel) component;
                  else if (component instanceof JScrollPane)
                      currentPanel = (JPanel) ((JScrollPane) component).getViewport().getComponent(0);
              }
          }
  
          return currentPanel;
      }
  </code></pre>