【发布时间】:2018-03-19 16:04:28
【问题描述】:
我正在为我正在创建的游戏制作编辑器,但我在实现可滚动的关卡概览时遇到了问题。概述应该有这样的布局:
Canvas 的大小应该始终为 1280x720,因此我想使用 JScrollPane 以便在 JFrame 变小时仍能查看整个画布。 现在为了实现这一点,我使用了 GridBagLayout 并在画布上设置了首选大小。问题是扩展 JFrame 最终将允许您将画布扩展到超出其首选大小。为了阻止这种情况,我将滚动窗格视口的布局设置为 FlowLayout 以防止它调整其持有的视图的大小。这似乎造成了两个问题:
1 : GridBagLayout 在展开到全屏时不再正确分配空间。
2:当您使 ScrollPane 小于其视口视图时,视图会被截断,滚动似乎也不起作用。
总结我的问题:
是否有另一种/更好的方法来实现此 UI,如果没有,我如何解决 gridbaglayout 在扩展到全屏并切断视口视图时无法正确分配空间的问题?
这里是我用于示例的代码:
public class Main extends JFrame {
public Main() {
this.setSize(800, 400);
this.setMinimumSize(new Dimension(400, 400));
this.setLocationRelativeTo(null);
JPanel optionsPanel = new JPanel();
optionsPanel.setBackground(Color.red);
JPanel scrollContentPane = new JPanel();
scrollContentPane.setPreferredSize(new Dimension(700,700));
scrollContentPane.setBorder(BorderFactory.createLineBorder(Color.red));
JScrollPane scrollPane = new JScrollPane();
scrollPane.getViewport().setLayout(new FlowLayout());
scrollPane.getViewport().setView(scrollContentPane);
scrollPane.setHorizontalScrollBarPolicy(scrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(scrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.fill = gc.BOTH;
gc.weightx = 1.0;
gc.weighty = 1.0;
gc.gridx = 0;
gc.gridy = 0;
contentPanel.add(optionsPanel, gc);
gc.gridx = 1;
contentPanel.add(scrollPane, gc);
this.setContentPane(contentPanel);
this.setVisible(true);
}
public static void main(String[] args) {
Main main = new Main();
}
}
这是我在程序中使用的实际代码:
previewPanel = new PreviewPanel(this);
controlPanel = new ControlPanel(this);
centerPanel = new JPanel();
centerPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = c.BOTH;
c.weightx = 1;
c.weighty = 1;
// #HACK, fill grids with empty labels
c.gridx = 0;
c.gridy = 0;
centerPanel.add(new JLabel(), c);
c.gridx = 1;
centerPanel.add(new JLabel(), c);
c.gridx = 2;
centerPanel.add(new JLabel(), c);
c.gridx = 3;
centerPanel.add(new JLabel(), c);
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
centerPanel.add(controlPanel, c);
c.gridx = 1;
c.gridy = 0;
c.gridwidth = 3;
centerPanel.add(previewPanel, c);
setLayout(new BorderLayout());
add(centerPanel, BorderLayout.CENTER);
add(menuBar, BorderLayout.NORTH);
}
【问题讨论】:
-
when expanded the gridbaglayout no longer distributes the space correctly.- 定义正确吗? GridBagLayout 首先为每个组件提供其首选大小。然后,如果有额外空间可用,该空间将根据您的权重进行划分,在本例中为 50/50。 -
正确地,因为我只使用两个网格单元,所以我希望它只占用屏幕的一半。您可以在屏幕截图中看到,虽然它占用更多,我该如何防止呢?