title: Listen for when a Component is Shown for the First Time
body: <p>I am trying to capture the very first moment when a component is shown on the screen without using 'dirty' solutions as with use of a timer.
  Basically, I want to know the moment when I can safely start using <code>getLocationOnScreen()</code> method on the component.</p>
  
  <p>I thought that component listener could help but no luck here. I am stuck for now and do not know which listener to use for this. Any suggestions?</p>
  
  <p>Here is some sample code which shows that a component listener fails.</p>
  
  <pre><code>import java.awt.Color;
  import java.awt.Dimension;
  import java.awt.event.ComponentAdapter;
  import java.awt.event.ComponentEvent;
  import java.awt.event.ComponentListener;
  import java.awt.event.MouseAdapter;
  import java.awt.event.MouseEvent;
  import java.awt.event.MouseListener;
  import javax.swing.JComponent;
  import javax.swing.JFrame;
  import javax.swing.JPanel;
  
  public class CompListenerTest
  {
      static ComponentListener cL = new ComponentAdapter()
      {
          @Override
          public void componentShown(ComponentEvent e)
          {
              super.componentShown(e);
              System.out.println("componentShown");
          }
      };
  
      static MouseListener mL = new MouseAdapter() 
      {
  
          @Override
          public void mousePressed(MouseEvent e)
          {
              super.mousePressed(e);
              JComponent c = (JComponent) e.getSource();
              System.out.println("mousePressed c="+c.isShowing());
          }
  
      };
  
      public static void main(String[] args)
      {
          JPanel p = new JPanel();
          p.setPreferredSize(new Dimension(300, 400));
          p.setBackground(Color.GREEN);
          p.addComponentListener(cL);
          p.addMouseListener(mL);
  
          System.out.println("initial test p="+p.isShowing());
          JPanel contentPane = new JPanel();
          contentPane.setBackground(Color.RED);
          contentPane.add(p);
          JFrame f = new JFrame();
          f.setContentPane(contentPane);
          f.setSize(800, 600);
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          f.setVisible(true);
      }
  }
  </code></pre>
  
  <p>Thanks in advance.</p>