Dillon Burton
Dillon Burton

Reputation: 363

Drawing a shape but keeping the most previous shape on screen in java

I've created a function to where I can click somewhere in a Jpanel and it draws a shape at the position where the mouse clicked. The problem I am having is when I click in a new position, it moves the shape and redraws it. I would like the previous shape to "Burn" into the screen and stay there. It doesn't have to have any data tied to it, I just want the image of the shape to show where it used to be each time. I have tried many different things, but no success. here is what I mean:

public void paintComponent(Graphics g) {

    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.BLUE);
    g2.fillRect(n, m, 32, 32); //I want each one of these shapes to be new, not
                                       //moving, but redrawn      

    ////////////////////////////////////////////////
    //This is just drawing a grid and doing other things(irrelevant)
    g2.fill(new Ellipse2D.Double(x, y, 32, 32));
    for (int i = 0; i < 500; i += 32) {
        g2.drawRect(i, j, 32, 32);
        for (int j = 0; j < 500; j += 32) {
            g2.drawRect(i, j, 32, 32);
        }
    }


    if (paintColBlock){
        System.out.println("Drawing Block at " + n +"," + m);
        paintColBlock = false;
    }
   /////////////////////////////////////////////////////////////////////    

}

Upvotes: 1

Views: 579

Answers (1)

Mordechai
Mordechai

Reputation: 16234

Keep an ArrayList of Points like this:

public void paintComponent(Graphics g) {

super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLUE);
for(Point p : points)
    g2.fillRect(p.x, p.y, 32, 32);

Adding a new Point to the array at each mouse click, and call repaint():

public void mousePressed(MouseEvent evt){
    points.add(new Point(evt.getX(),evt.getY());
    repaint();
}

Upvotes: 3

Related Questions