0

How can I get the size of a component when using a layout for my frame? I can just note that I'm using a BorderLayout for a JFrame and I want the size of a JPanel.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Shayan Toqraee
  • 735
  • 8
  • 18
  • 2
    Why do you need the size? Unless we know the requirement we can't make a suggestion. – camickr Jul 03 '13 at 16:11
  • The [preferred size](http://stackoverflow.com/q/7229226/230513) is determined by the content and layout of the enclosing container. – trashgod Jul 03 '13 at 19:59
  • @camickr I want to override the paint function to draw a grid on it. And I don't know how many lines to draw, and how long the lines should be. I don't want my class to be limited to manually designed frames. – Shayan Toqraee Jul 04 '13 at 07:46

1 Answers1

0

You can try the JPanel methods, getWidth() and getHeight():

int getWidth();
int getHeight();

They will return the height and width of the JPanel.

You can also get the bounds of the JPanel using the method getBounds():

Rectangle getBounds();

It will return a Rectangle of the bounds. You can use it to get the location and size of the JPanel.

Shayan Toqraee
  • 735
  • 8
  • 18
Iftikhar Ali Ansari
  • 1,650
  • 1
  • 17
  • 27
  • When the panel is placed in a frame using a layout, all the mentioned functions will return 0. – Shayan Toqraee Jul 04 '13 at 07:50
  • you are getting 0 because you calling the methods before your main frame is render. the above method is work only when you call after the setVisible(); or you can try pack() method. – Iftikhar Ali Ansari Jul 04 '13 at 18:29