在Java中绘制方形矩阵

时间:2012-12-28 00:38:36

标签: java matrix

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

以下是Matrica(Matrix)课程的代码(以我的母语为准,crtanjeMatrice表示drawMatrixduzinalength

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) {
    }

}

1 个答案:

答案 0 :(得分:0)

您目前正在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来呈现子组件。