【发布时间】:2022-01-05 01:25:00
【问题描述】:
我正在尝试创建 Game of Life 类型的应用程序,但在绘制单元格时遇到了一些问题。我有一个大的JPanel (RectGridPanel) 作为模拟的基础,在那个面板上我通过在GridLayout 中添加更小的面板(GridElement) 来绘制一个网格。然后我尝试将我的单元格添加到这些较小的面板中。
import java.awt.Dimension;
import java.awt.Color;
import java.awt.event.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
public class GridElement extends JPanel
{
public GridElement()
{
this.setLayout(new BorderLayout());
this.setMinimumSize(new Dimension(40, 40));
this.setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
public void createCell()
{
Cell newCell = new RectCell();
this.add(newCell, BorderLayout.CENTER);
}
}
import java.awt.*;
public class RectCell extends JPanel
{
public RectCell()
{
this.setPreferredSize(new Dimension(40, 40));
this.setBackground(Color.BLUE);
}
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.awt.Graphics;
public class RectGridPanel extends JPanel
{
public RectGridPanel()
{
this.setPreferredSize(new Dimension(840, 800));
this.setLayout(new GridLayout(20,21));
for(int x = 0; x < 21; x++)
{
for(int y = 0; y < 20; y++)
{
GridElement element = new GridElement();
element.createCell();
this.add(element);
}
}
}
}
我想要实现的是我的单元格(蓝色)填充了我创建的所有 GridElement 组件,但实际上,单元格的颜色越远离左上角,其尺寸就越小:
【问题讨论】:
-
一般情况下,您创建一个绘图JPanel 并绘制您的单元格。 Oracle 教程Performing Custom Painting 将向您展示如何操作。你可以看看这个版本的Conway's Game of Life。
-
如需更好的帮助,请edit添加minimal reproducible example。
-
顺便说一句:我有一些空闲时间,所以在这里把它变成了可运行的代码(一个 MRE)。在编译之前需要修复一个编译错误(
Cell newCell = new RectCell();->RectCell newCell = new RectCell();),然后..对我来说似乎很好。这是how it appears shrunken down。 注意: 为避免浪费您的时间,更重要的是浪费他人免费帮助的时间,请务必检查您的 MRE 代码是否真正显示错误。 -
是的,没有注意到,但这只是我在减少代码方面的错误(RectCell 扩展了单元格)。这也正是我正在寻找的行为,但我的看起来仍然受到干扰。
-
1) 你有太多级别的组件。您只需要一个“GridCell”来表示每个组件和一个“GridPanel”来保存网格布局中的所有 GridCell。我猜是因为您有一个包含一个面板的面板,该面板包含一个您有布局问题的面板。 2) 不要在“GridPanel”上使用
setPreferredSize()。布局管理器将根据添加到面板的组件确定大小。