Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 简单游戏抛出堆栈溢出错误_Java_Stack Overflow - Fatal编程技术网

Java 简单游戏抛出堆栈溢出错误

Java 简单游戏抛出堆栈溢出错误,java,stack-overflow,Java,Stack Overflow,我做了一个简单的游戏,在光标所在的位置画一个图像。它工作了一段时间,但很快就会抛出StackOverflowerr异常 public class Graphic extends JComponent { private ImageIcon imgIcon = new ImageIcon("/Users/Koolkids/Documents/codeStuff/Java/BattleOfTheEmojis/src/img/happy.png"); private Image img = imgIc

我做了一个简单的游戏,在光标所在的位置画一个图像。它工作了一段时间,但很快就会抛出StackOverflowerr异常

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)

并且永远如此。

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

每次需要更新/绘制组件时,Swing都会调用
paint
方法
repaint
方法安排组件进行重绘,这会导致调用
paint
。因此,在
paint
内部调用
repaint
是一种无休止的循环

侦听器只应添加一次到组件,例如,在创建组件时


当组件的表示形式发生更改时,应调用
repaint
,例如,在更改
光标后,在侦听器内部调用

,Java UI代码对此没有经验,但是-通过调用
this.addMouseMotionListener(m),您似乎正在每一帧添加一个新的事件侦听器,并删除
super.mouseMoved(e)