how to draw multiple rectangles

我们两清 提交于 2019-12-02 08:36:04

Painting is a destructive process. That is, when a new paint cycle runs, the previous contents of the Graphics context should be cleared...

So, in you paintComponent method you are only painting the last block...

if(isClicked = true){
    blocks[blocknum] = new Rectangle(50,50, xCreate, yCreate);
    g2d.setColor(Color.RED);
    g2d.fillRect(xCreate,yCreate,50,50);
    System.out.println(blocknum);
    repaint(); // THIS IS A BAD IDEA
}

DO NOT call any method that might cause repaint to be called. This will put you in a potential cycle of death that will consume your CPU.

Instead, you should loop through the blocks array and paint each one...

for (Rectangle block : blocks) {
    if (block != null) {
        g2d.setColor(Color.RED);
        g2d.fill(block);
    }
}

And in you mouseReleased method, you should be adding the new rectangles...

public void mouseReleased(MouseEvent event){
    blocknum=blocknum+1;
    if (blocknum < blocks.length) {
        xCreate=event.getX();
        yCreate=event.getY(); 
        blocks[blocknum] = new Rectangle(xCreate, yCreate, 50, 50);
    }
}

I'd suggest you take a look at Custom Painting, Painting in AWT and Swing and Concurrency in Swing for more details

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!