Search code examples
javajframegraphics2dmouselistener

Draw a car when mouse clicked JAVA


I have 2D-Graphic class to draw the car and I really need help to make the car appear when I click on the mouse. This is what I have so far.

public class CarMove extends JComponent

{

private int lastX = 0;

private int x = 1;
//create the car from draw class
Car car1 = new Car(x,320);

public void paintComponent(Graphics g)
{

     Graphics2D g2 = (Graphics2D) g;

     int carSpeed = 1;
     int w = getWidth(); 
     x = lastX + carSpeed;
     if (x == w - 60)
     {
        x = x - carSpeed;
     }

     FrameMouseListener listener = new FrameMouseListener();
     super.addMouseListener(listener);
     lastX = x; 
}
public class FrameMouseListener implements MouseListener
{

    @Override
    public void mouseClicked(MouseEvent e) 
    {
        Graphics2D g2 = (Graphics2D) g;
        car1.draw(g2);  
     }
  }
}

I add the mouselistener to the frame when I click on the frame the car will appear but I cant make it work in mouseClicked event to draw the car


Solution

  • Your code should look more like:

    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    
    import javax.swing.JComponent;
    
    public class CarMove extends JComponent
    
    {
    
        private volatile boolean drawCar = false;
    
        private int lastX = 0;
    
        private int x = 1;
        // create the car from draw class
        Car car1 = new Car(x, 320);
    
        {
    
            FrameMouseListener listener = new FrameMouseListener();
            super.addMouseListener(listener);
        }
    
        public void paintComponent(Graphics g)
        {
    
            Graphics2D g2 = (Graphics2D) g;
    
            int carSpeed = 1;
            int w = getWidth();
            x = lastX + carSpeed;
            if (x == w - 60)
            {
                x = x - carSpeed;
            }
            if (drawCar)
            {
                car1.draw(g2);
            }
    
            lastX = x;
        }
    
        public class FrameMouseListener extends MouseAdapter
        {
    
            @Override
            public void mouseClicked(MouseEvent e)
            {
                drawCar = true;
                repaint();
            }
        }
    
    }
    

    First of all, you need to add your listener only once at startup. Second, all drawing operations must be performed in painting mathods, you are not allowed to store the graphics object and draw to it from any place in your code. There is a special drawing thread, that may only touch this object. SO the rexcipe is, set up what should be painted (by some variables), prepare your painting method to properly use those variables, then call repaint() whern you would like to refresh the view.