我看不出如何用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));
}
}发布于 2016-07-05 01:03:34
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(),我也不会得到零的宽度和高度。
https://stackoverflow.com/questions/38192245
复制相似问题