Вылет объектов за пределы экрана в javax.swing
Пытаюсь сделать так чтобы у меня отрисовывалось 30 объектов по 10 каждого класса, Rectangle(простой прямоугольник), DrawableRect(прямоугольник с контуром), ColoredRect(закрашенный прямоугольник с контуром). Проблема в том, что для при работе прямоугольник вылетает за пределы экрана и при этом только за правую и нижнюю границы. В чем я ошибся? DrawableRect наследуется от Rectangle, ColoredRect от DrawableRect, все классы переопределяют метод draw.
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
public class Window extends JFrame{
private static final ArrayList<Rectangle> rectColorArr = new ArrayList<>();
private static Window gameWindow;
public static void main(String[] args) {
int k = 0;
while(k!=10){
rectColorArr.add(new Rectangle(0,100,0,150));
rectColorArr.add(new ColoredRect(0,100,0,100,Color.BLACK,Color.YELLOW));
rectColorArr.add(new DrawableRect(500,520,500,520,Color.CYAN));
k++;
}
gameWindow = new Window();
gameWindow.setResizable(false);
gameWindow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
gameWindow.setLocation(0,0);
gameWindow.setSize(1980, 1024);
Field field = new Field();
gameWindow.add(field);
gameWindow.setVisible(true);
}
private static void onRepaint(Graphics g,Rectangle rect){
rect.draw(g);
if((rect.x1 < 0)||(rect.x2 >= gameWindow.getWidth())) rect.dx=-rect.dx;
if((rect.y1 < 0)||(rect.y2 >= gameWindow.getHeight())) rect.dy=-rect.dy;
rect.x1 += rect.dx * 0.005f;
rect.x2 += rect.dx* 0.005f;
rect.y1 += rect.dy* 0.005f;
rect.y2 += rect.dy* 0.005f;
}
private static class Field extends JPanel{
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
for (Rectangle i: rectColorArr){
onRepaint(g,i);
}
repaint();
}
}
}
public class Rectangle{
protected float x1, x2, y1, y2,dx,dy;
public void draw(Graphics g){
float width = Math.abs(x2-x1);
float height = Math.abs(y2-y1);
g.drawRect((int)x1,(int)x2,(int)width,(int)height);
}
}
public class DrawableRect extends Rectangle{
protected Color outColor;
public DrawableRect(int x_1, int x_2, int y_1,int y_2, Color color){
super(x_1, x_2, y_1, y_2);
outColor = color;
}
public void draw(Graphics g){
float width = Math.abs(x2-x1);
float height = Math.abs(y2-y1);
g.setColor(outColor);
g.drawRect((int)x1,(int)y1,(int)width,(int)height);
}
}
public class ColoredRect extends DrawableRect{
private Color inColor;
public ColoredRect(int x_1, int x_2, int y_1, int y_2, Color color, Color colorIn){
super(x_1, x_2, y_1, y_2, color);
inColor = colorIn;
}
public void draw(Graphics g){
float width = Math.abs(x2-x1);
float height = Math.abs(y2-y1);
g.setColor(outColor);
g.drawRect((int)x1,(int)y1,(int)width,(int)height);
g.setColor(inColor);
g.fillRect((int)x1,(int)y1,(int)width,(int)height);
}
}