提问者:小点点

Java绘制类不显示矩形数组


我正在尝试打印一个矩形数组并在运行时出现错误。

我从我的主类发送一个数字,只是一个普通的int,例如5到我的油漆类中的getdataforshow(我发送的数字)函数。这会在if语句中进行一些检查,以便我们知道在哪里显示矩形。到目前为止,这在我的程序中运行良好。

现在它将其保存在矩形类中,然后在运行时显示所有矩形?

另外值得一提的是,我从这个网站上了解到,一个用户在这里发布了活动方法:https://tips4java.wordpress.com/2009/05/08/custom-painting-approaches/

我的绘画课是:

class mainPanel extends JPanel
{
    int processes, storedProcesses;

    //for inital values of rectangles
    int xCoor = 0;
    int yCoor = 0;
    int width = 10;
    int height = 50;

    static int x = 100;
    int [] y = {100,150,200,250,300,350,400,450,500,550};

    private ArrayList<ColoredRectangle> coloredRectangles = new ArrayList<ColoredRectangle>();

    class ColoredRectangle
    {
          private Rectangle rectangle;

          public ColoredRectangle()
          {
                 System.out.println("REC");
          }

        public Rectangle getRectangle()
        {
              return rectangle;
        }
    }

    public void addRectangle(ColoredRectangle rectangle)
    {
          coloredRectangles.add( rectangle );
          repaint();
    }

    public mainPanel(int processFROMmain)
    {
        //just some jpanel looks here
    }

    public Dimension getPreferredSize() {
        return new Dimension (1000, 1000);
    }

    public void getDataForDisplay (int proc)
    {
    //the method checks the value from "proc" to see where to display a rectangle on screen. proc comes from user i.e 5
    int loop = 0;

    while (loop < storedProcesses)
    {
        int breakloop = 0;

        if (proc == loop)
        {
            xCoor =  x;
            yCoor = y[loop];
            x = x + 10;
            breakloop = 1;
            Rectangle r = new Rectangle(xCoor, yCoor, width, height);
            ColoredRectangle cr = new ColoredRectangle();
            addRectangle( cr );
        }

        if (breakloop == 1)
        {
            break;
        }

        loop++;
    }
 }

  public void paintComponent(Graphics g) {
       super.paintComponent(g);   

    for (mainPanel.ColoredRectangle cr : coloredRectangles)
        {
        g.setColor(Color.RED );
        Rectangle r = cr.getRectangle();
        g.drawRect(r.x, r.y, r.width, r.height);
        }
    }  
}

我得到的错误是:


共2个答案

匿名用户

您实际上从未将Rectgle对象存储在您的ColoredRectange对象中。您正在初始化一个变量,私有Rectange rectange;但仅此而已。您应该编辑您的代码。

private Rectangle rectangle;

    public ColoredRectangle(Rectangle rectangle) {
        this.rectangle = rectangle;
}

并在getDataForDisplay方法中;

Rectangle r = new Rectangle(xCoor, yCoor, width, height);
ColoredRectangle cr = new ColoredRectangle(r);

匿名用户

您忘记将RectangeColoredRectange连接,因此当您尝试访问矩形的一个属性时,NPE。

的(快速

Rectangle r = new Rectangle(xCoor, yCoor, width, height);
ColoredRectangle cr = new ColoredRectangle();
cr.rectangle = r; //<-- adding this line
addRectangle( cr );