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

时间:2013-05-16 14:04:02

标签: java swing resize jframe jpanel

我是java新手,并且一直在使用this video来学习。当我运行程序时,窗口是空白的,直到我调整它为止。

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);

      }
  }

提前感谢任何能给我一些建议的人! 如果我要问的内容或我如何解释自己,请告诉我。

1 个答案:

答案 0 :(得分:3)

setVisible()之后立即致电pack()

提示:

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