Swing 中的 GridBagLayout 格式化

GridBagLayout formatting in Swing

当我添加第二行(按钮)时,我的文本区域消失了。

这是 GridBagLayout 代码:

    public void gridlayout(){

    setLayout(new GridBagLayout());

    GridBagConstraints grid = new GridBagConstraints();

    grid.gridy = 0;
    grid.gridx = 0;
    add(refreshButton, grid);

    grid.gridx = 1;
    grid.gridwidth = 4;
    add(textArea, grid);

    grid.gridy = 1;
    grid.gridx = 0;
    grid.anchor = GridBagConstraints.LINE_END;
    add(button1, grid);

    grid.gridx = 1;
    add(button2, grid);

    grid.gridx = 2;
    add(button3,grid);

    grid.gridx = 3;
    add(button4,grid);

    grid.gridx = 4;
    add(button5,grid);

    grid.gridx = 5;
    add(button6,grid);


}

如何使刷新按钮保持在左侧,文本区域出现在第二行上方并占据 gridx = 1 <----> gridx =5 space?

  • 您的 JTextArea 的 grid.gridx 应该是 1,它的 grid.gridwidth 应该是 5。
  • 如果您要在任何地方设置尺寸或首选尺寸,则不要。
  • 您应该将该 JTextArea 包装在 JScrollPane 中,并将滚动窗格添加到 GUI,而不是文本区域。
  • 如果您在显示之前不在顶层 window 上调用 pack(),请执行此操作。

例如:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;

public class GridBagExample extends JPanel {

   public GridBagExample() {
      setLayout(new GridBagLayout());

      add(new JButton("Refresh"), createGbc(0, 0));
      add(new JScrollPane(new JTextArea(12, 20)), createGbc(1, 0, 5, 1));


      for (int i = 0; i < 6; i++) {
         String text = "Button: " + (10 - i); 
         JButton button = new JButton(text);
         add(button, createGbc(i, 1));
      }
   }

   private GridBagConstraints createGbc(int x, int y) {
      return createGbc(x, y, 1, 1);
   }

   private GridBagConstraints createGbc(int x, int y, int w, int h) {
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = x;
      gbc.gridy = y;
      gbc.gridwidth = w;
      gbc.gridheight = h;
      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.insets = new Insets(2, 2, 2, 2);
      return gbc;
   }

   private static void createAndShowGui() {
      GridBagExample mainPanel = new GridBagExample();

      JFrame frame = new JFrame("GridBagExample");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}