简单的游戏抛出StackOverFlowError

时间:2016-11-18 12:36:25

标签: java stack-overflow

我做了这个简单的游戏,其中绘制了光标所在的图像。有一段时间它可以工作,但很快就会引发StackOverFlowError异常。

public class Graphic extends JComponent {
private ImageIcon imgIcon = new ImageIcon("/Users/Koolkids/Documents/codeStuff/Java/BattleOfTheEmojis/src/img/happy.png");
private Image img = imgIcon.getImage();
private Point cursor = new Point(0, 0);

public MouseMotionAdapter m = new MouseMotionAdapter() {
    @Override
    public void mouseMoved(MouseEvent e) {
        super.mouseMoved(e);
        cursor = e.getPoint();
    }
};



public void paint(Graphics g) {

    Graphics2D g2 = (Graphics2D) g;
    g2.setBackground(Color.WHITE);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    this.addMouseMotionListener(m);
    g2.drawImage(img, cursor.x - 11, cursor.y - 11, 22, 23, this);
    repaint();

}

}

输出

Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at java.awt.AWTEventMulticaster.mouseMoved(AWTEventMulticaster.java:329)
at java.awt.AWTEventMulticaster.mouseMoved(AWTEventMulticaster.java:329)
at java.awt.AWTEventMulticaster.mouseMoved(AWTEventMulticaster.java:329)

并永远继续这样。

1 个答案:

答案 0 :(得分:2)

请勿调用repaint,也不要在paint方法中添加侦听器。

每次需要更新/绘制组件时,Swing都会调用paint方法repaint方法会调度组件以进行重绘,这会导致paint被调用。因此,在repaint内调用paint是一种无限循环。

只应向组件添加一次侦听器,例如何时创建组件。

当组件的表示被更改时,应该调用

repaint,例如更改cursor后,在监听器内部。