单击Java

时间:2015-12-01 20:01:31

标签: java jframe mouseevent mouseclick-event

当我点击鼠标按钮时,我编写了一个绘制1辆汽车的程序,现在我想在鼠标按钮上第二次点击时再画一辆汽车。

@SuppressWarnings("serial")

公共类CarMove扩展了JComponent

{

private volatile boolean drawCar = false;
private volatile boolean drawCar1 = false;

private int lastX = 0;
private int clickCount = 0;

{
    FrameMouseListener listener = new FrameMouseListener();
    super.addMouseListener(listener);
}

public CarMove() 
{
    Thread animationThread = new Thread(new Runnable() 
    {
        public void run() 
        {
            while (true) 
            {
                repaint();
                try 
                {
                    Thread.sleep(10);

                } catch (Exception ex) {}
            }
        }
    });

    animationThread.start();
}
public void paintComponent(Graphics g)
{

     Graphics2D g2 = (Graphics2D) g;

     if (drawCar) 
     {
         int x = 1;
         int carSpeed = 1;
         int w = getWidth(); 
         x = lastX + carSpeed;
        //create the car from draw class
         Car car1 = new Car(x,320);
         car1.draw(g2);   
         lastX = x; 
     }   
     if (drawCar1) 
     {
         int x = 1;
         int carSpeed = 1;
         int w = getWidth(); 
         x = lastX + carSpeed;
        //create the car from draw class
         Car car2 = new Car(x,320);
         car2.draw(g2);   
         lastX = x; 
     }   
}
public class FrameMouseListener implements MouseListener
{

    @Override
    public void mouseClicked(MouseEvent ev) 
    {
        if (clickCount == 1)
        {
            drawCar = true;
            repaint();  
        }
        if (clickCount == 2)
        {
            drawCar1 = true;
            repaint();
        }

    }

我尝试创建布尔抽屉2次,但它没有用,请帮助我。

1 个答案:

答案 0 :(得分:1)

如果您需要知道用户点击了mouseButton的次数。

@Override
    public void mouseReleased(MouseEvent m) {
        int clickCount = m.getClickCount();

        //change your code to do draw the cars based on clicks
    }

修改

当你调用重绘方法时,第一行必须是:

super.repaint();

要绘制多辆汽车,当您调用 paint(Graphics g)时,必须使用循环:

public void paintComponent(Graphics g){
    super.repaint();

   Graphics2D g2 = (Graphics2D) g;

   for(int car=0; car<totalClicks; car++){

    //Here add your code to draw the cars
    if(car==1){
       //do this
    }else if(car==2){
       //do that
    }else if(car== 3){
       //do more
    }else if(car==4){
       //hard job 
    }//etc

 }