有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaJPanel和GridBagLayout

我想在JPanel中动态地放置按钮。为此,我选择将GridBagLayout应用于此面板(包含按钮的面板)

问题是我的按钮出现在面板中央,而我希望它们从上到下放置

这是我的密码:

void placerListeUsers(){

  jPanel49.setLayout(new GridBagLayout());
  //jPanel49 est le panel sur lequel je place mes boutons.
  //jPanel49 est placé dans une JScrollPane
  GridBagConstraints c = new GridBagConstraints();
  c.gridx = 0;
  c.fill = GridBagConstraints.HORIZONTAL;
  //c.anchor=GridBagConstraints.NORTH;

  c.weightx = 1;
  //c.weighty = 0;

  for (int i = 0; i < 5; i++) {
  c.gridwidth = GridBagConstraints.REMAINDER;
  c.gridy = i;
  jPanel49.add(new JButton("Super"), c);

}

他所生产的:

https://i.stack.imgur.com/4vBQj.png

谢谢你帮我解决这个问题


共 (2) 个答案

  1. # 1 楼答案

    the problem is that my buttons appear from the center of my panel while I would like them to be placed from top to bottom.

    需要指定WebXY/Y约束,否则组件会聚集在中间。

    阅读关于How to Use GridBagLayout的Swing教程。关于Specifying Constraints的部分将为您提供更多信息

    在我看来,你只有垂直按钮。也许将GridLayoutBoxLayout添加到帧的BorderLayout.PAGE_START中会更容易

  2. # 2 楼答案

    即使您没有按照要求提供MCVE。我试图为您的布局提供解决方案…;)

    问题是,正如camickr已经提到的,在计算按钮大小后,您需要告诉GridBagLayout将面板的所有额外空间放在哪里:

    • 锚定必须是网格约束。北方
    • weight需要为添加到面板的最后一个按钮设置为1

      public static void main(String[] args) {
      JFrame frame = new JFrame();
      
      frame.addWindowListener(new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
              System.exit(0);
          }
      });
      Container content = frame.getContentPane();
      GridBagLayout layout = new GridBagLayout();
      JPanel panel = new JPanel(layout);
      GridBagConstraints c = new GridBagConstraints();
      c.gridx = 0;
      c.fill = GridBagConstraints.HORIZONTAL;
      c.anchor = GridBagConstraints.NORTH;
      c.weightx = 1;
      int buttonCount = 5;
      for (int i = 0; i < buttonCount; i++) {
          c.weighty = i == buttonCount - 1 ? 1 : 0;
          c.gridwidth = GridBagConstraints.REMAINDER;
          c.gridy = i;
          JButton button = new JButton("Super");
          panel.add(button, c);
      }
      content.add(new JScrollPane(panel));
      frame.pack();
      frame.setSize(400, 400);
      frame.setVisible(true);
      }