Home > Java > javaTutorial > How to Gradually Rotate an Image in Swing?

How to Gradually Rotate an Image in Swing?

Susan Sarandon
Release: 2024-12-06 04:39:31
Original
1006 people have browsed it

How to Gradually Rotate an Image in Swing?

How to rotate an image gradually in Swing?

Swing provides several ways to rotate an image. One approach is to use the AffineTransform class, which allows you to apply a rotation transformation to an image.

To rotate an image gradually, you can use a Timer to update the rotation angle over time. Here is an example of how to do this:

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;
import javax.swing.Timer;

public class RotateImagePanel extends JPanel implements ActionListener {

    private Image image;
    private AffineTransform transform;
    private double angle;
    private Timer timer;

    public RotateImagePanel(Image image) {
        this.image = image;
        transform = new AffineTransform();
        angle = 0;
        timer = new Timer(100, this);
        timer.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.translate(getWidth() / 2, getHeight() / 2);
        g2.rotate(angle, image.getWidth(null) / 2, image.getHeight(null) / 2);
        g2.drawImage(image, transform, null);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        angle += Math.PI / 100;
        repaint();
    }
}
Copy after login

This code creates a JPanel that displays an image. The paintComponent method uses the AffineTransform class to rotate the image around its center by the specified angle. The Timer object is used to update the rotation angle over time.

You can add the RotateImagePanel to your Swing application by adding it to a JFrame or other container. The rotation animation will start automatically when the JFrame is displayed.

The above is the detailed content of How to Gradually Rotate an Image in Swing?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template