Swing中的GridBagLayout格式

时间:2015-05-19 22:41:17

标签: java swing layout-manager gridbaglayout

http://i.imgur.com/oxcEAT5.png

当我添加第二行(按钮)时,我的textArea消失了。

http://i.imgur.com/P9auZqi.png

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


}

如何使刷新按钮保持在左侧,textArea出现在第二行上方并占用gridx = 1< ----> gridx = 5空格?

1 个答案:

答案 0 :(得分:1)

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

例如:

enter image description here

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