[英]Stick more GridLayouted panels next to each other
我正在使用3个JPanels
生成一个棋盘,其中包含以下GridLayout
:
我正在使用可调整大小的JFrame来完全包含它。 我实际上使用了这个代码 ,稍加修改。
这意味着,在填充三个面板后,将它们添加到主JFrames面板,如下所示:
Container contentPanel = getContentPane();
/**Create some panels**/
JPAnel 8x8 = new JPanel();
8x8.setLayout(new GridLayout(8, 8));
JPAnel 1x8 = new JPanel();
8x8.setLayout(new GridLayout(1, 8));
JPAnel 8x1 = new JPanel();
8x8.setLayout(new GridLayout(8, 1));
/**Populate frames**/
...
/**Assign frames**/
contentPanel.add(8x8, BorderLayout.CENTER);
contentPanel.add(8x1, BorderLayout.SOUTH);
contentPanel.add(1x8, BorderLayout.WEST);
它并没有那么糟糕,但它仍然是这样的:
底线扩展到垂直线。 窗口越大,这个问题就越明显。
我想将标记线粘贴到棋盘上,这样每个数字都会与适当的线对齐。
我尝试将2x2布局分配给父帧contentPanel
但是,网格布局似乎要求所有元素都具有相同的大小,因此它只会为8x1
和1x8
创建更大的区域。
我的方法:
contentPanel.setLayout(new GridLayout(2, 2));
contentPanel.add(1x8); //vertical markers first
contentPanel.add(8x8); //Then the chessboard
//Create empty placeholder for bottom-right corner
JPanel empty = new JPanel();
contentPanel.add(empty);
//finally add bottom markers
contentPanel.add(2x1);
但结果更糟:
那么我该如何使用那些醉酒的网格布局呢? 或者我应该开始不一样?
编辑:使用gridBaglayout
:
contentPanel.setLayout(new GridBagLayout());
/**Follows as after contentPanel.setLayout(new GridLayout(2, 2)); in the prewious code**/
结果:
玩了一下之后:
/*VERTICAL MARKERS*/
//set vertical fill
c.fill = GridBagConstraints.VERTICAL;
//Set current possition to [0,0] in the grid
c.gridx = 0;
c.gridy = 0;
//Add them to panel
contentPanel.add(indexysvis, c);
/*CHESSBOARD*/
//set vertical fill to both horizontal and vertical
c.fill = GridBagConstraints.BOTH;
//Set current possition to [1,0] in the grid
c.gridx = 1;
c.gridy = 0;
contentPanel.add(sachovnice, c);
/*HORIZONTAL MARKERS*/
//set vertical fill to both horizontal
c.fill = GridBagConstraints.HORIZONTAL;
//Set current possition to [1,0] in the grid
c.gridx = 1;
c.gridy = 1;
contentPanel.add(indexyvodo,c);
它不会尝试适合窗口:
您可以使用带有条件检查的9x9
网格。 这将使事情变得更简单和更好。 使用条件检查可能生成此类布局可能如下:
GridLayout layout = new GridLayout(0,9);
jPanel1.setLayout(layout);
for(int row =0; row < 9; row++)
for(int col=0; col<9;col++)
{
JButton button = new JButton();
if(col==0 && row==8)
{ button.setEnabled(false);
button.setContentAreaFilled(false);
}
else if(col==0)
button.setText(""+(char)('A'+row));
else if(row == 8)
button.setText(""+(char)('A'+col - 1));
else if(col%2==0)
button.setBackground(Color.white);
else button.setBackground(Color.black);
jPanel1.add(button);
}
它将具有如下输出:
将gridBagLayout
也设置为contentPane
。 这会将您的面板放置在所需的位置。
要么使用9x9的一个面板(数字将与每个字段一样大)或使用GridBagLayout ,这将为您提供完全控制。 也就是说, GridBagLayout
是一个完整的PITA。 也许TableLayout更符合您的喜好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.