我正在编写游戏,我的项目结构如下:
我们有一个抽象类,所有其他类都是从它继承的。
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;
}
}
还有一些类作为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) {
}
}
我在JPanel中添加了一个来自RedBird类的对象,但是当我点击这个对象时,MouseListener
不起作用。问题是什么 ?任何人都可以给我一个解决方案。
提前致谢:)
答案 0 :(得分:5)
您尚未将鼠标侦听器“添加”到任何JComponent。这就是它无法正常工作的原因。 在您的bird类的构造函数中添加以下代码:
this.addMousListener(this);