-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)
,並繼續這樣下去。
沒有用過Java UI代碼的經驗,但是 - 它看起來像是通過在繪畫函數中調用'this.addMouseMotionListener(m);'來爲每一幀添加一個新的事件偵聽器。 –
並刪除'super.mouseMoved(e);' –