Why is my JFrame empty?

后端 未结 2 1013
青春惊慌失措
青春惊慌失措 2021-01-29 00:59

I can\'t seem to figure out why my JFrame is empty. Where am I going wrong?

import javax.swing.*; import java.awt.FlowLayout;

public class GUIExample extends JFr

2条回答
  •  故里飘歌
    2021-01-29 01:33

    You forgot to add the contentPane in your jFrame, something like this

    frame.setContentPane(panel);
    

    I notice you're using inheritance to build your jFrame, so in this case you need to instantiate your own class. I've refactored your code with the minimun to run an jFrame.

    public class GUIExample extends JFrame {
    
        JCheckBox box1 = new JCheckBox("Satellite Radio");
    
        public static void main(String[] args) {
            JFrame frame = new GUIExample("GUI Example");
            JPanel panel = new JPanel();
            panel.setLayout(new FlowLayout());
            panel.add(box1);
    
            frame.setContentPane(panel);
            frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
            frame.setSize(500, 500);
            frame.setVisible(true);
        }
    }
    

    Basically you create an JFrame, create an JPanel, add your components to this panel and set the panel to your frame with setContentPane(panel).

    I'm sorry I can't test this right now, so if someone could and fix if needed, would really appreciate, but is something like this.

提交回复
热议问题