2016-11-18 172 views
-1

我做了这个简单的游戏,其中的图像绘制在光标位置。有一段时间它的工作,但很快它会抛出一个StackOverFlowError异常。简单的游戏抛出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) 

,并继续这样下去。

+2

没有用过Java UI代码的经验,但是 - 它看起来像是通过在绘画函数中调用'this.addMouseMotionListener(m);'来为每一帧添加一个新的事件侦听器。 –

+0

并删除'super.mouseMoved(e);' –

回答

2

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

paint方法在每次需要更新/绘制组件时都由Swing调用repaint方法调度组件以进行重新绘制,这会导致调用paint。所以在paint里面调用repaint就是一个无限循环。

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

repaint应该在组件的表示被改变时被调用,例如,里面的听众更换后cursor

+0

谢谢!它现在完美。 –