从未调用过MouseListener类?

时间:2016-04-13 17:26:39

标签: java user-interface mouselistener

无论是否点击,我都不会调用代码段中的MouseListener类。我想知道我的Creature课程中是否需要其他任何东西,因为只有听众在场,对我来说效果不佳。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Creature 
{
  private static int catchCounter = 0, missCounter = 0;//Used to track the amount of misses and catches
  //----------------------------------------------------
  //Listener class to see if the creature was clicked on
  //----------------------------------------------------
  private class ClickListener implements MouseListener
  {
    public void mousePressed(MouseEvent event)
    {
      System.out.println("this works");
      if (GamePanel.xContainNeg < event.getX() &&  event.getX() < GamePanel.xContainPos)
      {
        if (GamePanel.yContainNeg < event.getY() && event.getY() < GamePanel.yContainPos)
        {
          catchCounter++;
          if (catchCounter == 10)
          {
            //Ends game if they won
            JOptionPane.showMessageDialog(null, "Congratulations! You won!");
            GamePanel.timer.stop();
          }
          else
          {
            //Continues game if not
            GamePanel.timer.restart();
            GamePanel.stats.setText("Catches: " + catchCounter + " \tMisses: " + missCounter);
          }                 
        }
        else 
        {
          missCounter++;
          if (missCounter == 10)
          {
            //Ends game if lost
            JOptionPane.showMessageDialog(null, "You missed 3 times! You lose!");
            GamePanel.timer.stop();
          }
          else
          {
            //continues game if not
            GamePanel.timer.restart();  
            GamePanel.stats.setText("Catches: " + catchCounter + " \tMisses: " + missCounter);
          }
        }
      }
      else 
      {
        missCounter++;
        if (missCounter == 10)
        {
          //ends game if lost
          JOptionPane.showMessageDialog(null, "You missed 3 times! You lose!");
          GamePanel.timer.stop();
        }
        else
        {
          //continues game if not
          GamePanel.timer.restart();
          GamePanel.stats.setText("Catches: " + catchCounter + " \tMisses: " + missCounter);
        }
      }
    }
    //Empty methods
    public void mouseReleased(MouseEvent event) {}
    public void mouseClicked(MouseEvent event) {}
    public void mouseExited(MouseEvent event) {}
    public void mouseEntered(MouseEvent event) {}
  }
}

1 个答案:

答案 0 :(得分:0)

这就是你拥有的一切吗?你的主要方法在哪里?您永远不会将鼠标侦听器实现为任何东西,您需要一个组件并添加鼠标侦听器,例如,如果您有JPanel

JPanel panel = new JPanel();
panel.addMouseListener(//*add mouse listener here*//);