Wstęp do animacji

package pl.am.swing.animtions;

import javax.swing.*;
import java.awt.*;

public class MyFrame extends JFrame {

    public MyFrame() {
        setTitle("Zdarzenia myszy");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1000, 600);

        add(new MyComponent());
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            MyFrame myFrame = new MyFrame();
            myFrame.setVisible(true);
        });

    }
}
package pl.am.swing.animtions;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyComponent extends JComponent {

    private int rectangleX = 500;
    private int rectangleY = 300;

    public MyComponent() {
        Timer timer = new Timer(40, e -> {
            rectangleX += 2;
            rectangleY += 2;

            repaint();
        });

        timer.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        Toolkit.getDefaultToolkit().sync();
        Graphics2D graphics2D = (Graphics2D) g;

        Point point = new Point(rectangleX -100, rectangleY -100);
        Dimension dimension = new Dimension(200, 200);

        Rectangle rectangle = new Rectangle(point, dimension);
        graphics2D.fill(rectangle);


    }
}

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *