I have text file that has multiple x and y coordinates. I'm reding them in and trying to send them to drawrect. The problem I'm having is that the drawRect will only draw the last x and y that is read in here is how I'm reading in.

for (int i=0; i<4; i++){
                    tln = strLine.substring(mRec,mRec+18);
                    x1 = Integer.parseInt(tln.substring(1,3));
                    y1 = Integer.parseInt(tln.substring(3,6));
                    x2 = Integer.parseInt(tln.substring(6,9));
                    y2 = Integer.parseInt(tln.substring(9,12));
                    dim1 = Integer.parseInt(tln.substring(12,14));
                    flag = tln.substring(14,15);
                    lPoint = Integer.parseInt(tln.substring(15,17));
                    lSec = " ";

                    mRec +=18;

                length = x2-x1;
                depth = y2-y1;

And here is the drawRect

g.drawRect(map.x1, map.y1, map.length, map.depth);

How do I get drawRect to draw all 4 rectangles?

4 Years
Discussion Span
Last Post by JamesCherrill

To hold the info for multiple rectangles you need multiple sets of coordinates (x1, y1, length, depth). You could use arrays to hold them, or some kind of List or Set from the Java API.

Edited by JamesCherrill


I tried arrays, but got an out of range error. And I tried putting the draw into a for loop, didin't work.


wanna bet that "but my prof hasn't told about those yet"?

Votes + Comments
yea, you're right. "my professor". this is for school sonny.....

Which handler are you using to draw? If you use the same one to draw, it will be overwritten everytime you draw a rectangle. It is similar to overwrite the same variable with different values in a loop. Once you are out of the loop, you have the last value assigned from the loop.


Taywin, I know thats what i'm doing. What I don't understand is how to get it to draw before it overites the values.I'm using paintComponent. Is that what you meant?


I forgot to mention the reason this is driving me crazy is because it's not static. All this info comes from a txt file and changes in every text file. The number and size of rectangles. I have it hard coded now and it works perfect, but I can't use it in real life. Which is what I need.


The variable sizes are handled by the x,y,w,h variables.
The variable number of rectangles is a good reason to use a List rather than an array to hold them. If you haven't covered Lists yet, then just allocate a "big enough" array - eg [10000] and have a variable that contains the number of rectangles actually stored in the array.

So: store all your rectangle data in array(s) or whatever, then in paintComponent loop through them drawing them one at a time.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.