JPanel不会出现在窗口中,除非我调整窗口的大小



我是java中的GUI新手,一直在使用此视频学习。当我运行程序时,窗口是空白的,直到我调整它的大小。

public class GUIProgram extends JFrame
   {    
   int screenWidth = 1000; //screenSize.width;
   int screenHeight = 800; //screenSize.height;
   public GUIProgram()
      {
      super("DATABASE");
      setSize(screenWidth, screenHeight);
      setVisible(true);
      setDefaultCloseOperation(EXIT_ON_CLOSE);

      JPanel p = new JPanel();
      JPanel p2 = new JPanel();
      JPanel p3 = new JPanel(new GridBagLayout());
      JButton b = new JButton("Button 1");
      JButton c = new JButton("Button 2");
      p.add(b);
      p.add(c);
          JCheckBox cb = new JCheckBox("Do you LOVE bacon?");
      JCheckBox cb2 = new JCheckBox("Do you LOVE cheese?");
      p2.add(cb);
      p2.add(cb2);
      JLabel label = new JLabel("This is a label");
      JTextArea tb = new JTextArea("this is a test area");
      JTextField textField = new JTextField("text field");
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.insets = new Insets(15,15,15,15);
          gbc.gridx = 0;
      gbc.gridy = 0;
      p3.add(label, gbc);
      gbc.gridx = 0;
      gbc.gridy = 1;
      p3.add(tb, gbc);
      gbc.gridx = 1;
      gbc.gridy = 2;
      p3.add(textField, gbc);
      add(p, BorderLayout.SOUTH);
      add(p3, BorderLayout.CENTER);
      add(p2, BorderLayout.NORTH);
      }
  }

提前感谢任何能给我一些建议的人!如果我所问的问题或我的解释有什么含糊不清的地方,请告诉我。

最后调用setVisible(),紧接pack()

提示:

setSize(screenWidth, screenHeight);不要设置顶层容器的大小。而是布局内容&call pack()

相关内容

最新更新