【发布时间】:2022-01-03 22:12:25
【问题描述】:
我是 Java 和用户界面的新手,但我对 Java 图形有疑问。我想要实现的是在 JPanel 上绘制网格,然后将自定义组件绘制到网格中。
这是我要在其上绘制网格的类(其基础扩展 JPanel)。
public class RectGridPanel extends GridPanel
{
List<Rectangle> rects;
public RectGridPanel(Simulator sim)
{
super(sim);
this.rects = new ArrayList<Rectangle>();
this.setLayout(new GridLayout(20,20));
for(int x = 1; x < 801; x += 40)
{
for(int y = 2; y < 801; y += 40)
{
Cell newCell = new RectCell(x, y, sim);
this.add(newCell);
}
}
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(Color.BLACK);
for(int x = 1; x < 801; x += 40)
{
for(int y = 2; y < 801; y += 40)
{
Rectangle rect = new Rectangle(x, y, 40, 40);
g2.draw(rect);
rects.add(rect);
}
}
}
}
这是我想在网格内绘制的单元格:
public class RectCell extends Cell
{
Rectangle shape;
public RectCell(int x, int y, Simulator sim)
{
super(x, y, sim);
shape = new Rectangle(x, y, CELL_SIZE, CELL_SIZE);
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(Color.BLACK);
g2.fill(shape);
}
}
【问题讨论】:
-
如需更好的帮助,请edit添加minimal reproducible example。
-
Cell和GridPanel是什么? -
rects.add(rect);这将在每次调用paintComponent()时将所有矩形添加到列表中。您应该只在创建时初始化列表一次。 -
您应该有一张图纸
JPanel负责所有图纸。您使用由一个或多个 Java getter/setter 类组成的逻辑模型来维护板的状态。绘图JPanel从逻辑模型中读取游戏状态并相应地绘制游戏板。您必须在游戏的每一帧中绘制所有内容。