鼠标点击JAVA时画一辆车

时间:2015-12-01 06:54:28

标签: java jframe graphics2d mouselistener

我有2D-Graphic课程来绘制汽车,当我点击鼠标时,我真的需要帮助才能让汽车出现。这是我到目前为止所做的。

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事件中工作以绘制汽车

1 个答案:

答案 0 :(得分:0)

您的代码应该更像:

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()whern你想刷新视图。