简体   繁体   中英

Timer is not starting in JPanel

I am trying to move an image in JPanel and the static variable x and y are the coordinates of red color changed in an other class using opencv. Here the timer is not starting. Please tell me where I am mistaken.

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);

    }
}

Everytime the timer fires the action event, you check if redPoint is not null, if it's null you just do nothing. But in your code redPoint is always null, that's why nothing happens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM