• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

generating squares

 
Steven Joost
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I need help, because my code doesnt do, what I want:

With this there should be five squares generated, but look yourself:



 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You've missed some things in your code, which is why you don't get the result you want.

In makeGUI() method you have:

which says: Create new CoalOre and add it to parent frame. The instance created has default values for X and Y and these are both zeros. Once added, paint method of that redefined panel is invoked, and that method is also wrong. What you are doing in it is you say: paint the same square on that CoalOre 5 times (with the given X=0 and Y=0 and width=height=50), so basically you are drawing 5 squares at the same position which is (0, 0).

setOreLocation() method is also wrong. First of all, you omitted braces after for loop, so only new CoalOre().X = r(0,10); is executed 5 times. After that, new CoalOre().Y = r(0,10); is executed only once. But it doesn't matter, since those statements are not doing what you want. What you did is you just created 6 temporary instances (5 in for + 1 after for loop) of CoalOre that do nothing.
 
Steven Joost
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a better method? ._.

I used brackets in the loops, it don't work too
 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One possible way would be to define a separate class to use as model for your rectangles. That one would contain these fields: x- and y-coordinate and width and height. Also, in your customized panel you can put (say) ArrayList of your model objects to be drawn.

At the point where you try to do something with that for loop, you would instantiate k (in your case 5) objects of your model class and put them in the ArrayList mentioned above. The paintComponent(...) method would then iterate that list and draw the rectangles that are in it.
 
Steven Joost
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Worked, many thanks! =)
 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, that was fast!

Any time, glad I could help!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic