Search code examples
javaswingjpaneljbuttonjlabel

No error shown but JButton and Label can't be seen


I'm new to coding and I am facing this problem where it doesn't show the JButton and JLabel that i added in the GUI. What have i done wrong and how do i fix it?

    import java.awt.ComponentOrientation;
    import java.awt.GridLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JLabel;

   public class MainMenu {

public static void main (String []args) { 

    JFrame frame = new JFrame ("Main Menu");
    frame.setSize(480,720);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(3,2,5,5));
    JButton meals = new JButton ("Meals");
    JLabel label = new JLabel ("Welcome back!");
    panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
    panel.add(meals);
    panel.add(label);
    frame.add(panel);
}


}

Solution

  • That happens because you frame.setVisible(true); before adding any components to it. You should add the components to the frame first, and then, use the setVisible method.

    panel.add(meals);
    panel.add(label);
    frame.add(panel);
    frame.setVisible(true); //visible after components added