2

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

      }
  }

提前感谢任何可以给我一些建议的人!如果我在问什么或我如何解释自己有歧义,请告诉我。

4

1 回答 1

3

最后调用setVisible(),紧随其后pack()

小费:

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

于 2013-05-16T14:07:53.997 回答