• Post Reply Bookmark Topic Watch Topic
  • New Topic

JFrame help  RSS feed

 
ah mer
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Below is the code to generate the random color,size and position of rectangles in a JFrame. my question is how can i make sure that the rectangle drawn is entirely inside the JFrame? Asume the frame is 500x500

int width = (int) ((Math.random() * 120) + 10);
int x = (int) ((Math.random() * 40) + 10);
int y = (int) ((Math.random() * 40) + 10);

g.fillRect(x,y,ht,width);

[/code]
 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

Did you try frame.pack()?
 
ah mer
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
K. Tsang wrote:Welcome to the Ranch.

Did you try frame.pack()?


omg i nv heard of pack() method in my course before! LOL! can you kindly please elaborate on the use of pack for my code?
appreciate your help thanks!
 
ah mer
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok i google about pack method. but even if i use pack(). how sure am i that all the random rectangle is drawn within the JFrame?
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> Asume the frame is 500x500

forget the frame size - DrawPanel needs to be given a preferred size of 500,500
then frame.pack() will give you a drawing area of 500,500
otherwise you'll lose space allocated to borders/titlebar.

you could check if x+width > 500, and y+height > 500
or you could get the width, deduct from 500, then generate a random number of that for x
e.g. width random number is 111, so generate random x - 0 to 389. (ditto for y)
 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another thing you should look at is what layout manager you using.

The default layout manager for JFrame is BorderLayout. For JPanel is FlowLayout.

Since your class extends JPanel, I assume you are adding this panel to your JFrame. You can always set your size (eg panel.setPreferredSize(Dimension)) to fit your content.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!