Zadanie z animacji – odbicia

Kody źródłowe z odcinka

package pl.am.swing.animtions2;

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

public class MyFrame extends JFrame {

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

        add(new MyComponent());
    }

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

    }
}
package pl.am.swing.animtions2;

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

public class MyComponent extends JComponent {

    private int rectangleX = 500;
    private int rectangleY = 0;

    private int maxWidth = 800;
    private int maxHeight = 600;

    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, rectangleY);
        Dimension dimension = new Dimension(50, 50);

        Rectangle limit = new Rectangle(0, 0, maxWidth, maxHeight);
        graphics2D.setPaint(Color.LIGHT_GRAY);
        graphics2D.fill(limit);

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


    }
}

Dodaj komentarz

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