How do i recalculate preferred size of a JComponent?
Asked Answered
O

1

7

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?

Oxalate answered 11/1, 2012 at 7:3 Comment(9)
Are you setting size on startup or after/on some event?Pleurodynia
Why on earth are you setting the preferred size to 0x0 for? setVisible(false) might be the effect you need.Alderson
@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.Oxalate
@William: before setting preferedSize to 0 save old preferedSize in some variable and then reuse it.Pleurodynia
@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.Oxalate
did you try setting the minimum size to 0x0?Jurdi
@yair: and what does that have anything to do with my problem?Oxalate
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?Jurdi
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 managerComely
B
11

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

Beatrizbeattie answered 11/1, 2012 at 10:25 Comment(1)
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.Oxalate

© 2022 - 2024 — McMap. All rights reserved.