BoxLayout 误解:strut

4

我正在使用Swing编写一个简单的输入框。我使用boxLayout创建了一个用户输入的简单GUI。问题是,在所有标签的JPanel和JTextFields的JPanel之间创建水平支撑会导致整个面板向下移动(奇怪)。这是整个面板的代码:

private JPanel secondCard() {

    //main panel. set the boxlayout
    secondCard = new JPanel();
    secondCard.setLayout(new BoxLayout(secondCard,BoxLayout.Y_AXIS));

    // create vertical strut for looks
    secondCard.add(Box.createVerticalStrut(20));

    // create title. center it.
    JLabel title = new JLabel("Configure main network parameters "); 
    title.setAlignmentX(CENTER_ALIGNMENT);
    secondCard.add(title);

    // create vertical strut for looks
    secondCard.add(Box.createVerticalStrut(20));

    // create panel for the description labels
    JPanel labelPanel = new JPanel();
    labelPanel.setLayout(new BoxLayout(labelPanel,BoxLayout.Y_AXIS));
    labelPanel.setAlignmentX(LEFT_ALIGNMENT);

    JLabel inPut =new JLabel("number of inputs");
    inPut.setAlignmentX(LEFT_ALIGNMENT);
    labelPanel.add(inPut);

    inPut =new JLabel("number of outputs");
    inPut.setAlignmentX(LEFT_ALIGNMENT);
    labelPanel.add(inPut);

    inPut =new JLabel("number of layers");
    inPut.setAlignmentX(LEFT_ALIGNMENT);
    labelPanel.add(inPut);

    JPanel textFieldPanel = new JPanel();
    textFieldPanel.setLayout(new BoxLayout(textFieldPanel,BoxLayout.Y_AXIS));
    textFieldPanel.setAlignmentX(LEFT_ALIGNMENT);

    JTextField inputTextField = new JTextField();
    inputTextField.setAlignmentX(LEFT_ALIGNMENT);
    textFieldPanel.add(inputTextField);
    inputTextField.setMinimumSize(new Dimension(0,0));

    inputTextField = new JTextField();
    inputTextField.setAlignmentX(LEFT_ALIGNMENT);
    textFieldPanel.add(inputTextField);
    inputTextField.setMinimumSize(new Dimension(0,0));

    inputTextField = new JTextField();
    inputTextField.setAlignmentX(LEFT_ALIGNMENT);
    textFieldPanel.add(inputTextField);
    inputTextField.setMinimumSize(new Dimension(0,0));

    textFieldPanel.setMaximumSize(new Dimension(50, labelPanel.getMaximumSize().height));

    JPanel inputPanel = new JPanel();
    inputPanel.setLayout(new BoxLayout(inputPanel,BoxLayout.X_AXIS));
    inputPanel.setAlignmentX(CENTER_ALIGNMENT);

    inputPanel.add(labelPanel);

    //this is the problem strut!! it causes inputPanel to shift downwards 
    inputPanel.add(Box.createHorizontalStrut(20));

    inputPanel.add(textFieldPanel);

    secondCard.add(inputPanel);

    return secondCard;
}

没有支撑杆时它看起来是这样的: enter image description here 有支撑杆时它看起来是这样的(我知道我很糟糕的图片编辑): enter image description here
3个回答

5
你正在向一个BoxLayout中添加一个Box结构体。
正如javadoc所述,createHorizontalStrut(int width)
创建一个不可见的、固定宽度的组件。在水平的box中,您通常使用此方法来强制两个组件之间有一定量的空间。在垂直的box中,您可能使用此方法来强制box至少为指定的宽度。除非有多余的空间,否则不可见的组件没有高度,此时它会占用可用空间的份额,就像没有最大高度的任何其他组件一样。
因此,它填充了标题JLabel和JPanel底部之间的高度。
您可能想考虑改用Box.createRigidArea(new Dimension(20, height)),其中height可以被指定或设置为labelPanel的高度。

或者,您可以重新考虑您的JPanel布局 - 参考可视化指南

作为以后的参考,如果您无法理解您的Swing布局,请尝试为您不确定的JComponent添加彩色LineBorder。在这种情况下,Box struts不是JComponent而是Component,所以您需要将它们放入一个JPanel中,但这至少会向您展示每个组件在顶层JPanel中占用了多少空间。


javax.swing.Box 是一个“使用 BoxLayout 对象作为布局管理器的轻量级容器”。Box.Filler 是一个静态嵌套类,与 BoxBoxLayout 配合使用效果非常好。 - trashgod

3

我将按钮面板("previous",“next”,“finish”和“cancel”)放置在contentPane.SOUTH。在contentPane的中心,我放置了一个具有卡片布局的JPanel。secondCard JPanel是上面显示的代码。它是布局的第二个卡片(名称不太合适,我知道)。这是一个好的方法吗?我选择BoxLayout,因为它简单易用,而且BorderLayout不好用。 - hasdrubal
@user1111:BorderLayout可以很好地工作,特别是如果与mKorbel建议的其他布局一起使用。给mKorbel加1分。 - Hovercraft Full Of Eels

2

下面是一个嵌套布局的示例,使用了BorderLayout、FlowLayout(JPanel的默认布局)和GridBagLayout:

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;

import javax.swing.*;

public class LayoutFoo {
   private static final String TITLE = "Configure Main Foobar Parameters";
   private static final String[] LABEL_TEXTS = {
      "Number of Spams", "Number of Frapzats", "Number of Zignuts"
   };
   private static final int TEXTFIELD_SIZE = 10;
   private static final Insets WEST_INSETS = new Insets(5, 5, 5, 10);
   private static final Insets EAST_INSETS = new Insets(5, 10, 5, 5);
   private static final int EB_GAP = 5;
   private Map<String, JTextField> textFieldMap = new HashMap<String, JTextField>();

   public JPanel getConfigFooPanel() {
      JPanel textFieldPanel = new JPanel(new GridBagLayout());
      for (int i = 0; i < LABEL_TEXTS.length; i++) {
         addTextAndField(textFieldPanel, LABEL_TEXTS[i], i);
      }

      int blVertGap = 20;
      JPanel borderLayoutPanel = new JPanel(new BorderLayout(0, blVertGap));
      borderLayoutPanel.setBorder(BorderFactory.createEmptyBorder(EB_GAP, EB_GAP,
            EB_GAP, EB_GAP));
      JLabel titleLabel = new JLabel(TITLE, JLabel.CENTER);
      borderLayoutPanel.add(titleLabel, BorderLayout.PAGE_START);
      borderLayoutPanel.add(textFieldPanel, BorderLayout.CENTER);

      JPanel outerWrapperFlowPanel = new JPanel();
      outerWrapperFlowPanel.add(borderLayoutPanel);

      return outerWrapperFlowPanel;      
   }

   public String getFieldText(String labelText) {
      JTextField field = textFieldMap.get(labelText);
      if (field == null) {
         return ""; // ?? throw exception
      } else {
         return field.getText();
      }
   }

   private void addTextAndField(JPanel panel, String text, int i) {
      JLabel label = new JLabel(text, JLabel.LEFT);
      JTextField textField = new JTextField(TEXTFIELD_SIZE);
      textFieldMap.put(text, textField);
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = 0;
      gbc.gridy = i;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;
      gbc.weightx = 1.0;
      gbc.weighty = 1.0;
      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.anchor = GridBagConstraints.WEST;
      gbc.insets = WEST_INSETS;
      panel.add(label, gbc);

      gbc.gridx = 1;
      gbc.anchor = GridBagConstraints.EAST;
      gbc.insets = EAST_INSETS;
      panel.add(textField, gbc);
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("LayoutFoo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new LayoutFoo().getConfigFooPanel());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接