我可以将paintComponents()添加到数组中吗?

时间:2014-11-20 13:32:02

标签: java arrays swing user-interface paintcomponent

这是一些更新的代码,我仍然无法更改单个矩形的颜色。我想使用一个名为spaces []的数组,它有15个元素,以决定汽车应该停放的位置。我想以某种方式比较我的Rectangle数组的最后一个元素与CarSpace数组进行比较......然后改变颜色。 这是我更新的代码..

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

1 个答案:

答案 0 :(得分:1)

使用x,y,w,h创建辅助类Rectangle,并使用它的数组进行绘制。

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);
    }

}

}