This is some updated code, I'm still having trouble changing the color of individual rectangles. I want to use an array called spaces[] which has 15 elements, in order to decide where a car should be parked. I'm thinking about somehow comparing the last element of my Rectangle array to compare to the CarSpace array... and then change the color. Here is my updated code..
package carManagement;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import javax.swing.JPanel;
public class CarPanel extends JPanel
{
CarSpace[] space= new CarSpace[15];
private final Rectangle[] rects;
private Color shapeColor = Color.RED;
public CarPanel()
{
rects = new Rectangle[]
{
new Rectangle(25, 35, 30, 80,"8"),
new Rectangle(65, 35, 30, 80,"7"),
new Rectangle(105, 35, 30, 80,"6"),
new Rectangle(145, 65, 30, 50,"2"),
new Rectangle(185, 65, 30, 50,"1"),
new Rectangle(25, 170, 30, 50,"13"),
new Rectangle(65, 170, 30, 50,"12"),
new Rectangle(105, 170, 30, 50,"11"),
new Rectangle(145, 170, 30, 50, "3"),
new Rectangle(190, 160, 92, 80, "Attendant Station"),
new Rectangle(25, 280, 30, 50, "15"),
new Rectangle(65, 280, 30, 50, "14"),
new Rectangle(105, 280, 30, 80, "10"),
new Rectangle(145, 280, 30, 80, "9"),
new Rectangle(185, 280, 30, 50, "5"),
new Rectangle(225, 280, 30, 50, "4")
};
}//end carPark
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.white);
for (int i = 0; i<15; i++) {
if(space[i] == null){
g.setColor(Color.BLACK);
g.drawString(rects[i].number, rects[i].x, rects[i].y);
g.setColor(Color.GREEN);
g.fillRect(rects[i].x, rects[i].y, rects[i].w, rects[i].h);
}
else{
System.out.println("RED SPACESSS");
}
}//end for
}//end paintComponent
}//end JPanel
Create helper class Rectangle with x,y,w,h and use array of it to paint.
public class CarPark extends JPanel {
private final Rectangle[] rects;
static class Rectangle {
int x,y,w,h;
public Rectangle(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
}
public CarPark(){
rects = new Rectangle[]{
new Rectangle(25, 35, 30, 80),
new Rectangle(50, 35, 30, 80)
};
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.white);
for (Rectangle rect : rects) {
g.fillRect(rect.x, rect.h, rect.w, rect.h);
}
}
}