简体   繁体   English

MouseListener在JLabel中不起作用

[英]MouseListener does not work in JLabel

I am programming the game that the structure of my project is as follows : 我正在编写游戏,我的项目结构如下:

We have an abstract class that all others are inherited from it. 我们有一个抽象类,所有其他类都是从它继承而来的。

    public abstract class Bird extends JLabel implements MouseListener {
        private static final long serialVersionUID = 1L;

        private int M_weight;
        private int M_radius;
        private long M_bornTime;
        private int M_maxBirdPower;
        private BirdState M_birdState;
        private boolean B_prepareToShoot;

        public Bird(int weight, int radius, long bornTime, int maxBirdPower,
                BirdState birdState) {
            this.M_weight = weight;
            this.M_radius = radius;
            this.M_bornTime = bornTime;
            this.M_maxBirdPower = maxBirdPower;
            this.M_birdState = birdState;
            this.B_prepareToShoot = false;
            this.addMouseListener(this);
        }

        public BirdState getBirdState() {
            return M_birdState;
        }
    }

And some classes as RedBird that inherited from Bird class and implements abstract function as well. 还有一些类作为RedBird继承自Bird类并实现抽象函数。

    public class RedBird extends Bird {
        private static final long serialVersionUID = 1L;

        public RedBird(int weight, int radius, long bornTime, int maxBirdPower,
                BirdState birdState) {
            super(weight, radius, bornTime, maxBirdPower, birdState);
        }

        @Override
        public void mouseClicked(MouseEvent arg0) {
                System.out.println("Clicked");
        }

        @Override
        public void mouseEntered(MouseEvent arg0) {
        }

        @Override
        public void mouseExited(MouseEvent arg0) {
        }

        @Override
        public void mousePressed(MouseEvent arg0) {
        }

        @Override
        public void mouseReleased(MouseEvent arg0) {
        }
    }

I added an object from RedBird class in JPanel, But when i click on this object, MouseListener does not work. 我在JPanel中添加了RedBird类中的对象,但是当我单击此对象时, MouseListener不起作用。 What is the problem ? 问题是什么 ? Could any one give me a solution. 任何人都可以给我一个解决方案。

Thanks in advance :) 提前致谢 :)

You haven't "added" your mouse listener to any JComponent. 您尚未将鼠标侦听器“添加”到任何JComponent。 That's why it isn't working. 这就是它无法正常工作的原因。 In your bird class' constructor add the following code: 在您的bird类的构造函数中添加以下代码:

this.addMousListener(this);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM