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



这是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空间?

最佳答案

您的JTextArea的grid.gridx应该为1,而其grid.gridwidth应该为5。
如果您在任何地方都没有设置大小或PreferredSizes。
您应该将该JTextArea包装在JScrollPane中,然后将滚动窗格添加到GUI中,而不是文本区域中。
如果您未在显示前在顶级窗口上调用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();
         }
      });
   }
}

关于java - Swing中的GridBagLayout格式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30337383/

10-10 16:34