当鼠标单击JAVA时绘制汽车

当鼠标单击JAVA时绘制汽车,java,jframe,graphics2d,mouselistener,Java,Jframe,Graphics2d,Mouselistener,我有2D图形类绘制汽车,我真的需要帮助,使汽车出现时,我点击鼠标。这就是我目前所拥有的 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

我有2D图形类绘制汽车,我真的需要帮助,使汽车出现时,我点击鼠标。这就是我目前所拥有的

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

当我单击框架时,我将鼠标侦听器添加到框架中汽车将出现,但我无法使其在mouseClicked事件中工作以绘制汽车

您的代码应该更像:

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();
        }
    }

}
首先,您只需要在启动时添加一次侦听器。
第二,所有绘图操作都必须在绘制方法中执行,不允许存储图形对象并从代码中的任何位置向其绘图。有一个特殊的绘图线程,它可能只接触这个对象。因此,rexcipe是,设置应该绘制的内容(通过一些变量),准备绘制方法以正确使用这些变量,然后在需要刷新视图时调用repaint()

哈哈,它的工作,但汽车没有像我期望的那样移动,但谢谢老兄。我修复了一些东西,现在它可以运行了,谢谢老兄。你爸爸最好,让我开心。