2012-03-25 33 views
3

我将KenKen作为使用java swing库的术语项目。为了对齐,我使用了gridbag和gridlayout,但现在我想添加一个JPanel组件到UI。这些截图会使问题更加清晰:使用GridLayout对jpanels组件进行垂直对齐

Before I click on the button in the lowest panel below http://i41.tinypic.com/288jo9.png

现在我选择了网格单元,而我想在最左边的面板中添加的各个候选。

This is what happens when I click the number buttons 2, 3, 4 http://i41.tinypic.com/14scr9e.png

它扰乱网格和面板的相邻对准。

下面是板与它们各自的布局:

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](http://sscce.org/)(作为**这篇文章的编辑)。顺便说一句 - 从来没有听说过'作物'? Alt-Print屏幕只截取活动的GUI。请参阅[如何创建屏幕截图?](http://meta.stackexchange.com/questions/99734/how-do-i-create-a-screenshot-to-illustrate-a-post)(有关制作*很棒*截图)。 – 2012-03-25 18:56:28

+0

已编辑! @AndrewThompson – faizanjehangir 2012-03-26 05:35:25

+2

我不知道你为什么回复我告诉我你的编辑。我仍然在等待*** SSCCE。*** – 2012-03-26 06:28:42

回答

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());