Listen for when a Component is Shown for the First Time

前端 未结 6 1575
日久生厌
日久生厌 2021-01-07 22:29

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

6条回答
  •  滥情空心
    2021-01-07 22:59

    Oddly, the ComponentListener works just fine when applied to the JFrame. Here is the altered source where I saw it work.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class CompListenerTest
    {
        static ComponentListener cL = new ComponentAdapter()
        {
            @Override
            public void componentShown(ComponentEvent e)
            {
                super.componentShown(e);
                System.out.println("componentShown");
            }
        };
    
        public static void main(String[] args)
        {
            JPanel p = new JPanel();
            p.setPreferredSize(new Dimension(300, 400));
            p.setBackground(Color.GREEN);
    
            System.out.println("initial test p="+p.isShowing());
            JPanel contentPane = new JPanel();
            contentPane.setBackground(Color.RED);
            contentPane.add(p);
            JFrame f = new JFrame();
            f.addComponentListener(cL);
            f.setContentPane(contentPane);
            f.setSize(800, 600);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setVisible(true);
        }
    }
    

提交回复
热议问题