【发布时间】:2016-09-22 10:19:52
【问题描述】:
我遇到了 BoxLayout JPanel 无法正确显示水平胶水的问题。我相信我已经将问题缩小到没有额外的水平空间供胶水拉动,因为刚性区域在每个面板之间创建空间没有问题。话虽如此,我似乎无法找到导致此问题的组件或设置。
这里是包含相关代码的方法(我已经用多行注释包围了添加水平胶水的代码部分):
public void initialize() {
scrollPanel.removeAll();
for (Item item : getController().getCart().getItemList()) {
//Container
itemContainerPanel = new JPanel();
itemContainerPanel.setBorder(new EmptyBorder(0, 10, 10, 0));
itemContainerPanel.setLayout(new BoxLayout(itemContainerPanel, BoxLayout.Y_AXIS));
//Content panel
itemPanel = new JPanel();
itemPanel.setLayout(new BoxLayout(itemPanel, BoxLayout.X_AXIS));
itemPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
//itemPanel.setBorder(new LineBorder(Color.BLACK));
itemContainerPanel.add(itemPanel);
//Details left
detailsLeftPanel = new JPanel();
detailsLeftPanel.setLayout(new BoxLayout(detailsLeftPanel, BoxLayout.Y_AXIS));
detailsLeftPanel.setAlignmentY(Component.TOP_ALIGNMENT);
titlePanel = new JPanel();
FlowLayout titlePanelLayout = new FlowLayout(FlowLayout.LEFT);
titlePanelLayout.setHgap(0);
titlePanelLayout.setVgap(0);
titlePanel.setLayout(titlePanelLayout);
productNameLabel = new JLabel();
productNameLabel.setAlignmentX(LEFT_ALIGNMENT);
productNameLabel.setAlignmentY(TOP_ALIGNMENT);
titlePanel.add(productNameLabel);
detailsLeftPanel.add(titlePanel);
datesBookedPanel = new JPanel();
FlowLayout datesBookedPanelLayout = new FlowLayout(FlowLayout.LEFT);
datesBookedPanelLayout.setHgap(0);
datesBookedPanelLayout.setVgap(0);
datesBookedPanel.setLayout(datesBookedPanelLayout);
datesBookedLabel = new JLabel();
datesBookedLabel.setAlignmentX(LEFT_ALIGNMENT);
datesBookedPanel.setAlignmentY(TOP_ALIGNMENT);
datesBookedPanel.add(datesBookedLabel);
detailsLeftPanel.add(datesBookedPanel);
//Details right
detailsRightPanel = new JPanel();
detailsRightPanel.setLayout(new BoxLayout(detailsRightPanel, BoxLayout.Y_AXIS));
detailsRightPanel.setAlignmentY(Component.TOP_ALIGNMENT);
removePanel = new JPanel();
removePanel.setLayout(new BoxLayout(removePanel, BoxLayout.X_AXIS));
detailsRightPanel.add(removePanel);
cartItemPriceLabel = new JLabel();
cartItemPriceLabel.setAlignmentY(Component.CENTER_ALIGNMENT);
removePanel.add(cartItemPriceLabel);
removeBtn = new JButton("Remove");
removeBtn.setAlignmentY(Component.CENTER_ALIGNMENT);
removePanel.add(removeBtn);
/* ITEM PANEL BUILD WITH HORIZONTAL GLUE */
itemPanel.add(detailsLeftPanel);
itemPanel.add(Box.createHorizontalGlue());
itemPanel.add(detailsRightPanel);
}
任何帮助将不胜感激。谢谢,祝您有愉快的一天。
编辑:
我添加了一张图片
显示上面代码部分的输出。我在图像上绘制的红线显示了放置水平胶水的位置。胶水应该将带有价格标签的面板和移除按钮推到右侧以填充窗口的宽度,但它没有。
【问题讨论】:
-
如需尽快获得更好的帮助,请发帖minimal reproducible example 或Short, Self Contained, Correct Example。
-
提示:在 SO 上发布您的问题之前,请消除对您的问题的阐述没有贡献的所有类的依赖关系。谁知道?也许通过一个简化的示例,您可以自己发现问题。
标签: java swing layout-manager boxlayout