Does placing setVisible() function in the beginning of the function be different when I placed it at the end of that function?

前端 未结 2 1833
春和景丽
春和景丽 2021-01-25 00:56

I\'m just new to Java GUI Programming and I\'m having a problem that the components inside my panel is missing when I place the setVisible()function at the beginnin

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-25 01:45

    As already pointed out in the comments and the other answer:

    You should call setVisible(true) at the end, after all components have been added.


    This does not directly answer your question. The answer to your question is: Yes, it makes a difference. If you call setVisible before all compoents have been added, it may work, in some cases, with some programs, on some PCs, with some Java versions, with some operating systems - but you always have to expect that it may not work as expected in some cases.

    You will find dozens of related questions here on stackoverflow and elsewhere. The usual symptoms of these problems are that some components are not displayed properly, and then suddenly appear when the window is resized. (Resizing a window basically triggers a layout and a repaint).


    The likeliness of unexpected behavior is increased when you violate the threading rules of Swing. And, in some sense, you did violate the threading rules of Swing: You should always create the GUI on the Event Dispatch Thread!

    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    
    public class SomeSwingGUI
    {
        public static void main(String[] args)
        {
            SwingUtilities.invokeLater(new Runnable()
            {
                @Override
                public void run()
                {
                    createAndShowGUI();
                }
            });
        }
    
        // This method may (and will) only be called
        // on the Event Dispatch Thread
        private static void createAndShowGUI()
        {
            JFrame f = new JFrame();
    
            // Add your components here        
    
            f.setVisible(true); // Do this last
        }
    }
    

    And by the way: Timothy Truckle pointed out in a comment that you should not invoke setVisible from the constructor. This is true. More importantly: You should usually not directly create a class that extends JFrame. (In some (rare!) cases, this is appropriate, but the general guideline should be to not extend JFrame)

提交回复
热议问题