Usa Peppy Usa Peppy - 2 months ago 15
Java Question

Simple JFrame doesn't show up

I'm learning how to make simple JFrame's and I did something wrong. I'm sure it's a quick fix. If somebody could tell me the things I'm doing wrong, I would greatly appreciate it. Thanks.

Oh... also... could you check up on this and tell me if they follow good practice? (Besides their naming conventions which I can easily tell are terrible.)

My class's code:

FlowLayout flow = new FlowLayout();
JPanel pan;
JFrame fra;
JButton but = new JButton();
JLabel lab = new JLabel();

public MainScreen(){
gui();
}


public void gui(){

fra = new JFrame("ATR Utilities");
fra.setVisible(true);
fra.setSize(400, 600);
fra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

pan = new JPanel(flow);
pan.setBackground(Color.CYAN);

but = new JButton("Test");
lab = new JLabel("Test label");

pan.add(but);
pan.add(lab);



}

public static void main(String[] args){
new MainScreen();
}

Answer

You aren't adding your panel to your frame, and you should add everything before you make it visible.

public void gui() {
    fra = new JFrame("ATR Utilities");
    fra.setSize(400, 600);
    fra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    pan = new JPanel(flow);
    pan.setBackground(Color.CYAN);

    but = new JButton("Test");
    lab = new JLabel("Test label");

    pan.add(but);
    pan.add(lab);
    fra.add(pan);
    fra.setVisible(true);
}