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

前端 未结 2 1861
春和景丽
春和景丽 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:56

    The components cannot be shown, because you add them after you call the setVisible() method of the Frame.

    The Componet's add() method changes layout-related information, and invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to display the added component, as pointed here .

    So in order to show the items, you should either call the revalidate() method of the frame or call setVisible() after all your components are added.

    Unless there is no special need, you should call setVisible() after you have added every other component.

    public class TestMain extends JFrame {
    
    public static void main(String[] args) {
       JFrame test = new TestMain();
       //if the setVisible() is called too early, you have to revalidate
       test.revalidate();
    }
    
    public TestMain() { 
        setFrame();
    }
    
    private void setFrame() {
        setSize(400,400);
        setResizable(false);
        setLayout(new FlowLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel(new FlowLayout());
        setVisible(true);
        JTextArea textArea1 = new JTextArea(25,15);
        textArea1.setWrapStyleWord(true);
        textArea1.setLineWrap(true);
        panel.add(textArea1);
        JScrollPane scroll = 
                new JScrollPane(panel, 
                        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 
                        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        // this method invalidates the component hierarchy.
        getContentPane().add(scroll);
    
    }
    

    }

提交回复
热议问题