gpt4 book ai didi

java - 在Java中绘制方阵

转载 作者:行者123 更新时间:2023-12-01 04:56:24 24 4
gpt4 key购买 nike

我正在练习 Java swing。我创建了一个矩阵作为 Rectangle2D 对象的二维数组。我已经设置了 MouseListener 来绘制被单击的方 block 。我已经设置了 for 循环来检查单击了哪个方 block 。当我点击一个正方形时,它会被涂成蓝色。问题是,当我点击另一个方 block 时,第一个方 block 变成白色,另一个变成蓝色。我的问题是,如何保留第一次点击的方 block 的颜色?

这是Matrica(Matrix)类的代码(在我的母语中,crtanjeMatrice意思是drawMatrixduzina长度

public class Matrica extends JPanel implements MouseListener {
Rectangle2D[][] matrica = new Rectangle2D[8][8];
Color boja = Color.white;
int a = 0;
int b = 0;

public Matrica() {
addMouseListener(this);
}

public void paint(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.clearRect(0, 0, this.getWidth(), this.getHeight());
crtanjeMatrice(g2);
g2.setColor(boja);
g2.fill(matrica[a][b]);

}




private void crtanjeMatrice(Graphics2D g2){
g2.setColor(Color.black);
int startX = 0;
int startY =0;
int duzina = 50;
for(int i=0; i < matrica.length; i++){
for(int j = 0; j < matrica.length; j++){
matrica[i][j] = new Rectangle2D.Double(startX,startY,duzina,duzina);
g2.draw(matrica[i][j]);
startX = startX + duzina;
}
startY = startY + duzina;
startX = 0;
}

}


@Override
public void mouseClicked(MouseEvent e) {
}

@Override
public void mousePressed(MouseEvent e) {
int m,n;
int x = e.getX();
int y = e.getY();
for(int i = 0; i < matrica.length; i++)
for(int j =0; j < matrica.length; j++)
if(matrica[i][j].contains(x, y)){
boja = Color.blue;
a = i;
b = j;
repaint();
}
}


@Override
public void mouseReleased(MouseEvent e) {
}

@Override
public void mouseEntered(MouseEvent e) {
}

@Override
public void mouseExited(MouseEvent e) {
}

}

最佳答案

您当前正在 paint 方法中绘制单个矩阵单元:

g2.fill(matrica[a][b]);

但您需要“记住”哪些矩形已被单击。为此,可以使用一个简单的List来存储已单击的矩形的索引。基于Point 类的类提供了一种在列表中存储行列索引信息的好方法。

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.clearRect(0, 0, this.getWidth(), this.getHeight());
crtanjeMatrice(g2);
for (MyRowColumn index : indexList) { // MyRowColumn based on Point
g2.setColor(Color.blue);
g2.fill(matrica[index.x][index.y]);
}
}
<小时/>

旁白:,不要使用覆盖 paint,而是覆盖 paintComponent 并记住调用 super.paintComponent > 渲染子组件。

关于java - 在Java中绘制方阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14063155/

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