Projekt. Etap 1 – poruszanie się piłki
Kody źródłowe z odcinka
package pl.am.swing.gra.etap1;
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.gra.etap1;
import javax.swing.*;
import java.awt.*;
public class MyComponent extends JComponent {
Ball rectangle1 = new Ball();
public MyComponent() {
Timer timer = new Timer(40, e -> {
rectangle1.updatePosition();
repaint();
});
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
Toolkit.getDefaultToolkit().sync();
Graphics2D graphics2D = (Graphics2D) g;
Rectangle limit = new Rectangle(0, 0, Utils.maxWidth, Utils.maxHeight);
graphics2D.setPaint(Color.CYAN);
graphics2D.fill(limit);
graphics2D.setPaint(Color.BLUE);
graphics2D.fill(rectangle1.getShape());
}
}
package pl.am.swing.gra.etap1;
import java.awt.*;
import java.awt.geom.Ellipse2D;
public class Ball {
private int x = 500;
private int y = 0;
private int width = 30;
private int height = 30;
private int speedX = 5;
private int speedY = 10;
public Ball() {
}
public Ball(int x, int y, int width, int height, int speedX, int speedY) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.speedX = speedX;
this.speedY = speedY;
}
public void updatePosition() {
x += speedX;
y += speedY;
if (x + width > Utils.maxWidth) {
x = Utils.maxWidth - width;
speedX = -speedX;
}
if (y + height > Utils.maxHeight) {
y = Utils.maxHeight - height;
speedY = -speedY;
}
if (x < 0) {
x = 0;
speedX = -speedX;
}
if (y < 0) {
y = 0;
speedY = -speedY;
}
}
public Shape getShape() {
return new Ellipse2D.Float(x,y, width, height);
}
}
package pl.am.swing.gra.etap1;
public class Utils {
public static int maxWidth = 800;
public static int maxHeight = 600;
}