单击鼠标时绘制汽车 JAVA

Draw a car when mouse clicked JAVA

我有 2D 图形 class 可以绘制汽车,我真的需要帮助才能在单击鼠标时显示汽车。这是我目前所拥有的。

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

我将 mouselistener 添加到框架中,当我点击框架时汽车会出现,但我无法让它在 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();
        }
    }

}

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