尝试使用 JPanel 制作一个可移动的对象,它有一个 ImageIcon,当我调整它的大小时,它会自动拉伸。现在,当我运行应用程序时,它会正确激活并显示图像。但是,当我按下按钮时,它会显示以下错误消息:
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at java.awt.Component.setLocation(Unknown Source)
at tutorial.GridPanel.move(GridPanel.java:51)
at java.awt.Component.setLocation(Unknown Source)
at tutorial.GridPanel.move(GridPanel.java:51)
at java.awt.Component.setLocation(Unknown Source)
at tutorial.GridPanel.move(GridPanel.java:51)
(continue many times)
发现它可能是间接递归之王?东西,但我就是找不到是什么原因造成的。以下是我为 JPanel 编写的类 GridPanel。
package tutorial;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import darrylbu.icon.StretchIcon;
public class GridPanel extends JPanel
{
private BufferedImage image;
GridPanel() {}
GridPanel(String path)
{
setLayout(null);
try
{
image = ImageIO.read(new File(path));
}catch(IOException e)
{
System.out.println(e);
}
addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
System.out.println(e.getKeyChar());
move(10, 10);
}
});
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
StretchIcon icon = new StretchIcon(image);
icon.paintIcon(this, g, 0, 0);
}
public void move(int x, int y)
{
super.setLocation(getX() + x, getY() + y);
}
}
在这里:
public void setLocation(int x, int y)
{
move (x, y);
}
这是 Component.setLocation(( 的源代码。如您所见:该方法调用move()
。面板覆盖move()
以调用setLocation()
。我们开始:你的递归不是"间接的",它就在那里。
很明显:不要从您的move()
方法调用setLocation()
!所以你的整个方法在这一点上是有缺陷的。