Zadanie z animacji – odbicia. Rozwiązanie
Kody źródłowe z odcinka
package pl.am.swing.animtions3;
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.animtions3;
import javax.swing.*;
import java.awt.*;
public class MyComponent extends JComponent {
private int rectangleX = 500;
private int rectangleY = 0;
private int rectangleWidth = 50;
private int rectangleHeight = 50;
private int speedX = 5;
private int speedY = 10;
private int maxWidth = 800;
private int maxHeight = 600;
public MyComponent() {
Timer timer = new Timer(40, e -> {
rectangleX += speedX;
rectangleY += speedY;
if (rectangleX + rectangleWidth > maxWidth) {
rectangleX = maxWidth - rectangleWidth;
speedX = -speedX;
}
if (rectangleY + rectangleHeight > maxHeight) {
rectangleY = maxHeight - rectangleHeight;
speedY = -speedY;
}
if (rectangleX < 0) {
rectangleX = 0;
speedX = -speedX;
}
if (rectangleY < 0) {
rectangleY = 0;
speedY = -speedY;
}
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(rectangleWidth, rectangleHeight);
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);
}
}