我没有看到如何使用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));
}
}
答案 0 :(得分:3)
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(),我的宽度和高度都不会为零。