aspose file tools*
The moose likes Beginning Java and the fly likes generating squares Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "generating squares" Watch "generating squares" New topic
Author

generating squares

Steven Joost
Greenhorn

Joined: Sep 29, 2012
Posts: 28
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

Joined: Jun 19, 2010
Posts: 825
    
    5

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.


The quieter you are, the more you are able to hear.
Steven Joost
Greenhorn

Joined: Sep 29, 2012
Posts: 28
Is there a better method? ._.

I used brackets in the loops, it don't work too
Kemal Sokolovic
Bartender

Joined: Jun 19, 2010
Posts: 825
    
    5

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

Joined: Sep 29, 2012
Posts: 28
Worked, many thanks! =)
Kemal Sokolovic
Bartender

Joined: Jun 19, 2010
Posts: 825
    
    5

Well, that was fast!

Any time, glad I could help!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: generating squares