使用GridLayout对JPanel的组件进行垂直对齐

3

我正在使用Java Swing库制作KenKen术语项目。为了对齐,我使用了GridBag和GridLayout,但现在我想将另一个JPanel组件添加到UI中。这些屏幕截图将更清楚地说明问题:

Before I click on the button in the lowest panel below

现在我选择左侧面板中要添加相应候选项的网格单元格。

This is what happens when I click the number buttons 2, 3, 4

它会干扰网格和面板之间的相邻对齐。
以下是具有各自布局的面板:
 JPanel buttonPanel = new JPanel();
 buttonPanel.setLayout(new GridLayout(1, 4, 5, 5));
 buttonPanel.setPreferredSize(new Dimension(20,40));
 buttonPanel.add(undoButton);
 buttonPanel.add(redoButton);
 buttonPanel.add(eraseButton);
 buttonPanel.add(hintButton);

 JPanel cellPanel = new JPanel();
 cellPanel.setName("cellPanel");
 cellPanel.setLayout(new GridLayout(pSize, pSize, 0, 0));

 JPanel numPanel = new JPanel();
 numPanel.setName("numPanel");
 numPanel.setLayout(new GridLayout(1,1,5,5));
 numPanel.setPreferredSize((new Dimension(50,60)));

 JPanel candPanel = new JPanel();
 candPanel.setName("candidatesPanel");
 JLabel candidates = new JLabel("Candidates");
 candidates.setFont(new Font("Courier New", Font.ITALIC, 14));
 candidates.setForeground(Color.GRAY);
 candPanel.setLayout(new GridLayout(0,1));
 candPanel.add(candidates);

然后所有内容都进入内容面板:
 content.add(buttonPanel, pos.nextCol().expandW());
 content.add(candPanel, pos.nextRow());
 content.add(new Gap(GAP) , pos.nextRow());  // Add a gap below
 content.add(cellPanel, pos.nextCol());
 content.add(numPanel,pos.nextCol().expandW());

按钮都是在运行时生成的,并且它们会在操作监听器中添加到candPanel。

2
"我将在下一篇帖子中分享代码。" 为了更快地获得帮助,请发布一个SSCCE(作为帖子的编辑)。顺便说一句,从未听说过“crop”?Alt-Print Screen可以将屏幕截图裁剪为仅包含活动GUI。请参阅如何创建屏幕截图?(有关制作精美屏幕截图的提示)。 - Andrew Thompson
2
我不知道你为什么回复我告诉我你的编辑情况。我仍在等待一个SSCCE - Andrew Thompson
如果您提供完整的源代码以帮助调试和更好地理解情况,更多的人将愿意提供帮助。 - Zecas
1个回答

0

你似乎正在使用我不知道的GridBagConstraints子类(变量pos),尽管我可以从上下文中猜出它的功能。

假设您的问题是希望candidates面板在cellPanel的左侧而不是上方,您需要交换添加candPanelnew Gap(GAP) 的行,如下所示:

content.add(buttonPanel, pos.nextCol().expandW());
content.add(new Gap(GAP), pos.nextRow());   // These two lines
content.add(candPanel, pos.nextRow());      // swapped over
content.add(cellPanel, pos.nextCol());
content.add(numPanel,pos.nextCol().expandW());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接