我正试图弄清楚如何正确地循环鼠标事件



我正在执行一项任务,其中图像四处移动,当用户单击面板时,图像停止。当用户再次单击面板时,图像开始显示。到目前为止,我只能在图像继续运行之前启动和停止一次图像。我需要帮助来循环这个过程,这样用户就可以不断地启动和停止图像。

这是我的代码

Main:

import javax.swing.*;
public class Rebound {
//-----------------------------------------------------------------
   //  Displays the main frame of the program.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      JFrame frame = new JFrame ("Rebound");
      frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new ReboundPanel());
      frame.pack();
      frame.setVisible(true);
   }
}

面板:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ReboundPanel extends JPanel
{
   private final int DELAY = 10, IMAGE_SIZE = 35;
   private ImageIcon image;
   private Timer timer;
   private int x, y, moveX, moveY;
   public ReboundPanel()
   {
      timer = new Timer(DELAY, new ReboundListener());
      addMouseListener (new StopListener());
      image = new ImageIcon ("happyFace.gif");
      x = 0;
      y = 40;
      moveX = moveY = 3;
      setPreferredSize (new Dimension(1900, 1000));
      setBackground (Color.black);
      timer.start();
   }

   public void paintComponent (Graphics page)
   {
      super.paintComponent (page);
      image.paintIcon (this, page, x, y);
   }

   private class ReboundListener implements ActionListener
   {
      public void actionPerformed (ActionEvent event)
      {
         x += moveX;
         y += moveY;
         if (x <= 0 || x >= 1900-IMAGE_SIZE)
            moveX = moveX * -1;
         if (y <= 0 || y >= 1000-IMAGE_SIZE)
            moveY = moveY * -1;
         repaint();
      }
   }
   //  Represents the action listener for the timer.
   public class StopListener extends MouseAdapter
   {
       public void mouseClicked (MouseEvent event)
   {
            if (event.getButton() == MouseEvent.BUTTON1)
            {
                timer.stop();
            }
            addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent event) {
                    if(event.getButton() == MouseEvent.BUTTON1)
                    {
                        timer.start();
                        removeMouseListener(this);
                    }
                }
            });
    }
   }
}

您可以简单地重用同一个侦听器,并在启动/停止计时器之前检查计时器的状态:

public void mouseClicked(MouseEvent event)
{
    if (event.getButton() == MouseEvent.BUTTON1)
    {
        if (timer.isRunning()) {
            timer.stop();
        }
        else {
            timer.start();
        }
    }
}

在您的StopListener类中有一个实例变量bool isMoving = true;

然后在您的处理程序中应该使用它来确定是停止还是启动计时器:

public void mouseClicked( MouseEvent event )
{
    if( event.getButton() == MouseEvent.BUTTON1 )
    {
        if( isMoving )
            timer.stop();
        else
            timer.start();
        isMoving = !isMoving;
    }
}

最新更新