我看不到如何使SpringLayout的JPanel正确计算其首选大小,因为当前始终为(0,0)。我尝试调用panel.setPreferredSize(layout.preferredLayoutSize(panel));,但是它没有任何改变。我还尝试将约束(在下面的代码中注释掉)放置在面板的南侧和东侧,相对于最南侧/东侧的组件,并且虽然它开始给我合适的首选大小,但是在调整JFrame的大小时,GUI绝对搞砸了(例如某些组件移出视线,彼此重叠等)。

这是给我一些问题的课程:

public class TileView extends JPanel {

    private TilesController controller;

    private JRadioButton paint, select;
    private JPanel prototype_panel, selection_panel;

    public TileView (TilesController tiles_controller) {
        controller = tiles_controller;
        SpringLayout layout = new SpringLayout();
        setLayout(layout);

        prototype_panel = new TileBrushPanel(controller);
        selection_panel = new TileSelectionPanel(controller);
        paint = new JRadioButton("draw");
        paint.addActionListener(l -> controller.setPaintTileMode());
        select = new JRadioButton ("select");
        select.addActionListener(l -> controller.setSelectMode());

        ButtonGroup bGroup = new ButtonGroup();
        bGroup.add(paint);
        bGroup.add(select);

        layout.putConstraint(NORTH, paint, 4, NORTH, this);
        layout.putConstraint(WEST, paint, 4, WEST, this);
        add (paint);

        layout.putConstraint(NORTH, select, 0, NORTH, paint);
        layout.putConstraint(WEST, select, 4, EAST, paint);
        add (select);

        layout.putConstraint(NORTH, prototype_panel, 4, NORTH, paint);
        layout.putConstraint(WEST, prototype_panel, 4, WEST, this);
        add (prototype_panel);

        layout.putConstraint(NORTH, selection_panel, 0, NORTH, prototype_panel);
        layout.putConstraint(WEST, selection_panel, 4, EAST, prototype_panel);
        add (selection_panel);

        //layout.putConstraint(SOUTH, this, 4, SOUTH, prototype_panel);
        //layout.putConstraint(EAST, this, 0, EAST, selection_panel);
        setPreferredSize(layout.preferredLayoutSize(this));

    }

}

最佳答案

SpringLayout工作正常。您第一次做对了;您应该取消对最后两个putConstraint调用的注释,并删除setPreferredSize调用。

无法获得预期结果的原因可能是由于以下原因:

layout.putConstraint(NORTH, prototype_panel, 4, NORTH, paint);


您可能想写成:

layout.putConstraint(NORTH, prototype_panel, 4, SOUTH, paint);


通过将prototype_panel的北边缘与油漆的北边缘对齐,同时将其两个西边缘与容器的西边缘对齐,可以使它们重叠。

SpringLayout很难使用。我认为,最好使用其他布局或布局组合。彼此嵌套许多面板没有错。

就您而言,我相信您可以使用Box实例完成相同的布局:

Box radioButtons = Box.createHorizontalBox();
radioButtons.add(paint);
radioButtons.add(select);

Box panels = Box.createHorizontalBox();
panels.add(prototype_panel);
panels.add(selection_panel);

Box windowContents = Box.createVerticalBox();
windowContents.add(radioButtons);
windowContents.add(panels);

setLayout(new BorderLayout());
add(windowContents);


它虽然不短,但是却易于阅读和理解。

至于为什么宽度和高度为零的原因,我只能猜测您是在进行验证之前打印出了首选尺寸。甚至使用您的SpringLayout代码,将TileView面板添加到JFrame并在其上调用pack()时,宽度和高度都不会为零。

10-05 19:02