【问题标题】:Unable to set BoxLayout(JPanel) correctly in GridLayout/FlowLayout无法在 GridLayout/FlowLayout 中正确设置 BoxLayout(JPanel)
【发布时间】:2016-03-20 02:50:04
【问题描述】:

我有一个带有以下代码的面板

public class PhotoBox extends JPanel {


    private JLabel photoIcon;
    private JLabel photoName;
    private JLabel print;
    private ImageHelper imageHelper;


    public PhotoBox(File file, JLabel print) throws IOException {

        imageHelper = new ImageHelper();
        this.photoIcon =  new JLabel();
        this.photoIcon.setIcon(imageHelper.createThumbnails(file));
        this.photoIcon.setMaximumSize(new Dimension(200, 150));
        this.photoIcon.setAlignmentX(Component.CENTER_ALIGNMENT);

        this.photoName = new JLabel();
        photoName.setText((file.getName().length()) > 20 ? file.getName().substring(0,10)+".." : file.getName());
        this.photoName.setAlignmentX(Component.CENTER_ALIGNMENT);


        this.print = new JLabel();
        this.print.setText(print.getText());
        this.print.setAlignmentX(Component.CENTER_ALIGNMENT);

        setLayout(new BoxLayout(this , BoxLayout.Y_AXIS));
        setBorder(BorderFactory.createLineBorder(Color.black));
        //setPreferredSize(new Dimension(200,150));

        add(this.photoIcon);
        add(this.photoName);
        add(this.print);
    }
}

现在我将此类面板的列表添加到另一个具有 GridLayout 的 JPanel 中

JPanel tile = new JPanel();
GridLayout layout = new GridLayout(0,4);
tile.setLayout(layout);
PhotoBox vBox = new PhotoBox(file,filePrints.get(file.getName()));
tile.add(vBox);

但我最终得到的是这样的东西

我不明白为什么我的所有 PhotoBox 对象都占用了额外的空间。我希望图像靠得很近。不要忘记,我已经尝试过 PrefSize(),但它不起作用。

使用 WrapLayout/FlowLayout

编辑:

现在我觉得问题在于PhotoBoxBoxLayout

【问题讨论】:

    标签: java swing jpanel grid-layout


    【解决方案1】:

    请检查图像的高度,因为布局是正确的 AFAICS,没有别的。 :D

    【讨论】:

    • 谢谢,问题出在哪里
    【解决方案2】:

    这就是GridLayout 的本质。它占用可用空间并将其平均分配给所有组件。看看How to Use GridLayout

    如何解决将归结为您想要的。您可以使用GridBagLayout,但您将负责提供确定每个组件位置的约束。

    您还可以查看 Rob Camick 的 Wrap Layout。这是一个FlowLayout,因为它可能应该完成,因为它为组件提供了换行。

    您应该查看A Visual Guide to Layout Managers 以获得更多想法。

    你也可以考虑看看MigLayout

    【讨论】:

    • WrapBox 有帮助。但是如果你清楚地看到 PhotoBox 上已经放置了边框并且它似乎占用了很多空间,我该如何减少呢?
    • WrapLayoutFlowLayout 的扩展,您可以通过构造函数更改hgapvgap,尝试将0, 0 传递给它
    • 这不是 WrapLayout 的问题。问题出在 Jpanel 的 BoxLayout 上。我的 PhotoBox 占用的空间超过了所需的空间,将其他元素向下推。我需要知道一种减少这种情况的方法。
    【解决方案3】:

    GridLayout 将填充它所在的可用空间。因此,添加title 的容器实际上必须具有可用的高度,并且 Gridlayout 正在填充它。

    存在三个修复选项:

    • 为您的标题使用不同的布局管理器
    • 为要添加它的容器使用不同的布局。
    • 将您的标题放入具有 FlowLayout 的新 JPanel 中,然后将此“中间人”JPanel 添加到您的顶部容器中,而不是“标题”

    【讨论】:

      猜你喜欢
      • 2013-09-15
      • 2020-01-07
      • 1970-01-01
      • 2019-03-17
      • 1970-01-01
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多