gpt4 book ai didi

java - JPanel 中的计时器未启动

转载 作者:行者123 更新时间:2023-11-30 03:13:44 25 4
gpt4 key购买 nike

我正在尝试在 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);

}
}

最佳答案

每次计时器触发操作事件时,您都会检查 redPoint 是否不为 null,如果为 null,则什么都不做。但在您的代码中 redPoint 始终为 null,这就是为什么什么也没有发生。

关于java - JPanel 中的计时器未启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33102827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com