简体   繁体   中英

Adding a panel to a JFrame

There are no errors in the code but i cant seem to see the Jlabels in the window. Im not sure if the panel was added or if the jlabels were added to the panel .

public class JDemoResistance extends JFrame{

    private final JButton button1;
    private JPanel panel;
    private final int WINDOW_WIDTH = 320;
    private final int WINDOW_HEIGHT = 320;

    public JDemoResistance() {
        super("JDemoResistance");

        setSize(WINDOW_WIDTH, WINDOW_HEIGHT);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //JLabels Configs
        JLabel label1 = new JLabel("Too expensive");
        JLabel label2 = new JLabel("Bad reviews");
        JLabel label3 = new JLabel("Bad quality");
        JLabel label4 = new JLabel("Not worth it");
        JLabel label5 = new JLabel("Dosent work");

        //Button Configs
        button1 = new JButton("Button");
        button1.addActionListener(new ButtonListener());

        //Panel Configs
        panel = new JPanel();
        panel.add(label1);
        panel.add(label2);
        panel.add(label3);
        panel.add(label4);
        panel.add(label5);
        panel.add(button1);
        setVisible(true);
    }

      private class ButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e){

        }
    }      

    public static void main(String[] args) {
        JDemoResistance jdr = new JDemoResistance();

    }


}

You haven't added the panel to the frame, that's why you can't see any of the components. Add it before setting the JFrame visible.

 //Add the panel to the frame
 this.add(panel)
 setVisible(true);

You must add the panel to the JFrame as well.

panel.add(...);
add(panel); // <-- you forgot this
setVisible(true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM