我知道这个问题已经有答案了,但我觉得你应该看一下GridLayout的工作原理。首先,http://java.sun.com/docs/books/tutorial/uiswing/layout/gridbag.html和http://www.cs.ubc.ca/local/computing/software/jdk-1.5.0/docs/api/java/awt/GridBagConstraints.html有助于解密长而神秘的方法签名。
这个大富翁游戏板示例有三个主要部分。第一部分是布局的设置,第二部分是将大中央块添加为JPanels,第三部分是将外部正方形添加为JPanels。
public class GridBagLayoutExample extends JFrame {
public static void main(String[] args) {
new GridBagLayoutExample().setVisible(true);
}
public GridBagLayoutExample() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
GridBagLayout thisLayout = new GridBagLayout();
thisLayout.rowWeights = new double[] { 0.2, 0.1, 0.1, 0.1, 0.1,
0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2 };
thisLayout.columnWeights = new double[] { 0.2, 0.1, 0.1, 0.1, 0.1,
0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2 };
getContentPane().setLayout(thisLayout);
int gridX = 0;
int gridY = 0;
for (int j = 0; j < 4; j++) {
for (int i = 0; i < 13; i++) {
JPanel tempPanel = new JPanel();
switch(j)
{
case 0:
gridX = i;
gridY = 0;
break;
case 1:
gridX = 0;
gridY = i;
break;
case 2:
gridX = 12;
gridY = i;
break;
case 3:
gridX = i;
gridY = 12;
break;
}
getContentPane().add(tempPanel,
new GridBagConstraints(gridX,
gridY,
1,
1,
0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
tempPanel.setBorder(BorderFactory
.createLineBorder(Color.BLACK));
}
}
{
JPanel innerPanel = new JPanel();
getContentPane().add(
innerPanel,
new GridBagConstraints(1,
1,
11,
11,
0.0, 0.0,
GridBagConstraints.CENTER,
GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
}
pack();
setSize(260, 260);
} catch (Exception e) {
e.printStackTrace();
}
}
}
从这里开始,如果您添加一个结构来容纳面板,然后您可以向每个面板添加按钮和任何您想要的内容。按钮也可以替代面板。只要正确导入,这应该可以编译,所以编译并尝试一下。