gpt4 book ai didi

java - 在 JPanel 中获得良好的网格布局

转载 作者:行者123 更新时间:2023-12-02 02:11:36 25 4
gpt4 key购买 nike

我正在开发一个项目,在该项目中我用一个简单的软件模拟(康威的)生命游戏。后端部分已完成,但我在很好地显示单元格时遇到一些麻烦。我想要实现的是拥有 y 行和 x 列(x 和 y 可能因模拟而异)。每个单元都可以是活的(某种颜色)或死的(另一种颜色),我希望它们是正方形或至少接近正方形。我还需要能够修改特定的单元格,例如第 5 行第 3 列的单元格可能需要变成不同的颜色而不影响其他单元格。

由于这些要求,我目前正在使用 GridBagLayout,但没有得到所需的结果。我面临两个问题:

  1. 我只能获取一行,而我可以修改我拥有的列数
  2. 我不知道如何制作每个单元格的正方形,它们有时会水平/垂直拉伸(stretch)

我当前的代码正在闲逛,直到获得正确的形状:

    //Set grid dimensions
int gridSizeX = 5;
int gridSizeY = 5;
JFrame f;
JPanel p;

//Set the frame
f = new JFrame("Window");
f.setSize(600,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set the panel
p = new JPanel();
p.setLayout(new GridBagLayout());
p.setBackground(Color.blue);

//Set the constraints
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = 0.5;

//The panel that will hold the grid
JPanel a;

//Cycle through all fields of the grid and alternate between red and yellow fields
for (int i = 0; i < gridSizeX; i++)
{
for (int j = 0; j < gridSizeY; j++)
{
a = new JPanel();
if (i%2==0)
a.setBackground(Color.yellow);
else
a.setBackground(Color.red);
c.gridx = i;
c.gridy = j;
p.add(a, c);
}
}

//Make sure the frame and panel are shown
f.add(p);
f.setVisible(true);

最佳答案

  1. 您会获得更多行,但不同行的列的颜色相同。因此,您看不到差异。使用(i+j)%2
  2. 除了c.weightx = 0.5之外,您还应该设置c.weighty = 0.5

关于java - 在 JPanel 中获得良好的网格布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49923182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com