Java GUI shows blank until resize

孤街醉人 提交于 2020-01-11 11:36:49

问题


I have written a java gui code for many options available on it. the gui is also set visible true but it doesn't show until I pick its border and drag them to resize the gui window. After manually resizing it, it shows everything. Also, the textlabels and the textfields and buttons are not in new lines, they are placed one after one. Please tell me whats wrong with that: here is a part of code:

public static void initGUI(){
        JFrame fr = new JFrame(); 
        Container cont = fr.getContentPane();
        cont.setLayout( new FlowLayout( ) );    
        FlowLayout layout = new FlowLayout(); 
        cont.setLayout(layout); 
        frame.setSize(200,300) ;
        frame.setVisible(true) ;

        JTextField tName = new JTextField(30); 
        JTextField tCNIC = new JTextField(15); 

        JLabel nameLabel = new JLabel("Name:");
        JLabel cnicLabel = new JLabel("CNIC #:");


        cont.add(nameLabel);
        cont.add(tName);
        cont.add(cnicLabel);
        cont.add(tCNIC);


        JButton Cancel = new JButton ("Canel" );
        JButton OK = new JButton ("OK" );
        savebtn.setPreferredSize(new Dimension(150, 50));
        retbtn.setPreferredSize(new Dimension(150, 50));
        cont.add(savebtn);
        cont.add(retbtn);


        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    }

回答1:


frame.setVisible(true) ;

The above statement should be invoked AFTER all the components have been added to the frame. So it should be the last statement in your method.

Also, you should be invoking:

frame.pack();

instead of setSize(), before making the frame visible so all the components are displayed at their preferred size.



来源:https://stackoverflow.com/questions/50545296/java-gui-shows-blank-until-resize

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!