我有一个 JFrame,它在窗口的左上角添加一个 Pane 。效果很好。由于某种原因,组成左上角 Pane 的 gridbaglayout 的行为并不完全像我想要的那样。
我添加的前三个按钮位于第一个 y 行内并水平添加,但我添加到 gridY = 1 的 informationPane 不会转到下一行,它只是像按钮一样添加到右侧。
此外,我必须在每个按钮上设置首选大小,因为 iPadY 不会垂直扩展按钮。
private JPanel setUpTop()
{
JPanel pane = new JPanel();
pane.setLayout(new GridLayout(1, 2));
JPanel controlPane = new JPanel();
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
controlPane.setBackground(Color.RED);
c.gridx = 0;
c.gridy = 0;
previousSongBT = new JButton("<<");
previousSongBT.setPreferredSize(new Dimension(CTRL_BT_WIDTH, CTRL_BT_HEIGHT));
controlPane.add(previousSongBT, c);
c.gridx = 1;
c.gridy = 0;
playBT = new JButton(">");
playBT.setPreferredSize(new Dimension(CTRL_BT_WIDTH, CTRL_BT_HEIGHT));
controlPane.add(playBT, c);
c.gridx = 2;
c.gridy = 0;
nextSongBT = new JButton(">>");
nextSongBT.setPreferredSize(new Dimension(CTRL_BT_WIDTH, CTRL_BT_HEIGHT));
controlPane.add(nextSongBT, c);
c.gridx = 0;
c.gridy = 1;
c.weighty = 1;
c.gridwidth = 3;
c.anchor = GridBagConstraints.PAGE_END;
JPanel informationPane = new JPanel();
informationPane.add(new JButton("Bottom pane"));
informationPane.setBackground(Color.GREEN);
controlPane.add(informationPane, c);
pane.add(controlPane);
return pane;
}
这是添加该 Pane 的代码:
//Top-Left
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.insets = new Insets(20,20,0,0); //top padding
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.weighty = 0.5;
this.getContentPane().add(setUpTop(), c);
为了更清晰起见,这是一张图片,我希望绿色面板位于其他三个按钮下方:
最佳答案
而不是
JPanel controlPane = new JPanel();
pane.setLayout(new GridBagLayout());
应该是这样的
JPanel controlPane = new JPanel();
controlPane.setLayout(new GridBagLayout());
不应该吗?
关于java - GridBagLayout ipadY 和定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12990257/