我正在尝试在JPanel中移动图像,静态变量x和y是使用opencv在其他类中更改的红色坐标。这里的计时器没有启动。请告诉我哪里弄错了。
class ImageFollowingPanel extends JPanel
{
private final BufferedImage image;
private Point imagePosition = new Point(150, 150);
private Point redPoint;
private double imageAngleRad = 0;
public static int x, y;
public ImageFollowingPanel()
{
BufferedImage i = null;
try
{
i = ImageIO.read(new File("forward.png"));
}
catch (IOException e)
{
e.printStackTrace();
}
image = i;
ActionListener taskPerformer = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
if (redPoint != null)
{
int centerX = imagePosition.x + (image.getWidth() / 2);
int centerY = imagePosition.y + (image.getHeight() / 2);
if (redPoint.x != centerX)
{
imagePosition.x += redPoint.x < centerX ? -1 : 1;
}
if (redPoint.y != centerY)
{
imagePosition.y += redPoint.y < centerY ? -1 : 1;
}
System.out.println("mouse::: x : " + x + "y :" + y);
redPoint.x = x;
redPoint.y = y;
double dx = x - imagePosition.getX();
double dy = y - imagePosition.getY();
imageAngleRad = Math.atan2(dy, dx);
repaint();
}
}
};
Timer timer = new Timer(1000, taskPerformer);
timer.start();
}
protected void paintComponent(Graphics gr)
{
super.paintComponent(gr);
Graphics2D g = (Graphics2D) gr;
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
int cx = image.getWidth() / 2;
int cy = image.getHeight() / 2;
AffineTransform oldAT = g.getTransform();
g.translate(cx + imagePosition.x, cy + imagePosition.y);
g.rotate(imageAngleRad);
g.translate(-cx, -cy);
g.drawImage(image, 0, 0, null);
g.setTransform(oldAT);
}
}
答案 0 :(得分:2)
每次定时器触发动作事件时,都会检查redPoint
是否为空,如果为空,则不执行任何操作。但是在你的代码中redPoint
总是为空,这就是没有任何反应的原因。