6

I know the fact that when I create an instance of a JComponent, it has it's own preferred size. Now let's suppose that I setPreferredSize that JComponent manually with a dimension of 0 x 0. And i want that Component to "reset" its own preferredSize. How do I do that?

William Wino
  • 2,879
  • 6
  • 34
  • 58
  • Are you setting size on startup or after/on some event? – Harry Joy Jan 11 '12 at 07:06
  • Why on earth are you setting the preferred size to 0x0 for? `setVisible(false)` might be the effect you need. – Andrew Thompson Jan 11 '12 at 07:17
  • @Andrew in my case, the layoutManager set its space based on the component's preferredSize. So if i just setVisible(false) the component the blank space is still visible, thus I need to setPreferredSize the component. But in the other event i need to set its preferredSize back to the original. – William Wino Jan 11 '12 at 07:21
  • @William: before setting preferedSize to 0 save old preferedSize in some variable and then reuse it. – Harry Joy Jan 11 '12 at 07:24
  • @Harry thanks harry, I've done something similar to that. But I'm not convinced that that's the best way to do it. How does java calculate the component's default preferred size? I think that's the proper way to recalculate it. – William Wino Jan 11 '12 at 07:32
  • did you try setting the minimum size to 0x0? – yair Jan 11 '12 at 07:51
  • @yair: and what does that have anything to do with my problem? – William Wino Jan 11 '12 at 08:43
  • Depends on your layout manager, if the minimum size of the component is 0x0 and visible=false - I'd expect it to resize the component to its minimum size (instead of keeping an empty space). BTW, what *is* your layout manager? – yair Jan 11 '12 at 10:29
  • never-ever touch the setXXSize, instead use a LayoutManager which behaves as you require. Here the requirement is to ignore invisible components (which nearly all core managers do), so either find the toggle in the manager which controls the include/ignore invisible or use another manager – kleopatra Jan 11 '12 at 11:54

1 Answers1

10

1) Setting preferred size to null should reset the component back to getting its preferred size calculated as if it was never set.

component.setPreferredSize(null);

This might not do what you want, depending on how you signal that the layout should be redone - but at least it is technically the answer to your question.

2) It is generally advised to not use setPreferredSize, see this post

Community
  • 1
  • 1
Tormod
  • 454
  • 3
  • 7
  • Ah! You're a lifesaver. Thanks man! I should've read the documentation first. The problem is that the layout manager require me to specify the preferred size because it needs it to calculate the space. – William Wino Jan 11 '12 at 14:10