我试图在每个列上创建JPanel
与GridBagLayout
和面板。但是当我运行程序时,我总是在网格上得到一个面板,尽管我有一个循环来创建10X10的面板。
ColumnPanel
public class BoardColumnPanel extends JPanel {
public BoardColumnPanel() {
this.setBackground(Color.GRAY);
this.setSize(48, 48);
}
}
网格视图public class BoardPanel extends JPanel {
private GridBagLayout layout;
public BoardPanel() {
initBoardPanel();
}
private void initBoardPanel() {
layout = new GridBagLayout();
this.setLayout(layout);
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
// fill grid
BoardColumnPanel column;
for (int row=0;row<10;row++) {
for (int col=0; col < 10; col++) {
column = new BoardColumnPanel();
gridBagConstraints.gridx = col;
gridBagConstraints.gridy = row;
gridBagConstraints.ipadx = 5;
gridBagConstraints.ipady = 5;
layout.setConstraints(column,gridBagConstraints);
this.add(column);
}
}
}
}
我建议使用GridLayout,注意通过使用这个LayoutManager每个JComponents将在屏幕上有相同的大小,
您的代码没问题。让我们改变BoardColumnPanel
的背景颜色:
public class BoardColumnPanel extends JPanel {
public BoardColumnPanel(int i) {
this.setBackground(new Color(10 * i, 10 * i, 10 * i));
this.setSize(48, 48);
}
}
并初始化为不同的灰色:
public class BoardPanel extends JPanel {
private GridBagLayout layout;
public BoardPanel() {
initBoardPanel();
}
private void initBoardPanel() {
layout = new GridBagLayout();
this.setLayout(layout);
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
// fill grid
BoardColumnPanel column;
for (int row = 0; row < 10; row++) {
for (int col = 0; col < 10; col++) {
column = new BoardColumnPanel(row + col);
gridBagConstraints.gridx = col;
gridBagConstraints.gridy = row;
gridBagConstraints.ipadx = 5;
gridBagConstraints.ipady = 5;
layout.setConstraints(column, gridBagConstraints);
this.add(column);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame();
f.getContentPane().add(new BoardPanel());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}
我不完全确定,但我想说GridBagConstraints = new GridBagConstraints();需要在 for循环内的。否则,您将重复为相同的约束设置gridx/gridy。