1
我正在嘗試在JPanel中移動圖像,而靜態變量x和y是使用opencv在另一個類中更改的紅色座標。這裏計時器沒有啓動。請告訴我我錯在哪裏。計時器不在JPanel中啓動
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);
}
}