Re: Setting size for JLabel
sale31805@yahoo.com wrote:
The situation is like this. I have some components within JPanels.
JPanel adapts it's size to the size of the components. During the
runtime components are changing so it also changes the JPanels size.
Is it possible to determine some fixed size for JPanel so it doesn't
depend on the components which it contains?
I've tried with setPrefferedSize(), but size remains the same.
It's frame application with BoxLayout manager. JPanels also use
BoxLayout manager.
Normally, I think setPrefferedSize() works, but for Panels their job is
to change size, so they don't "remember" the size you set, because
that's not the point.
Off the top of my head, you could:
1. Make a new type of JPanel that does stick to a set size:
class MyFubarPanel extends JPanel {
//I don't like this idea...
}
2. Forgo a layout manager and position the components yourself (call
setLocation() on each). Call setLayout( null ) to remove the default
one. This is not recommended either but it might be the easiest for a
simple dialog that only runs on one platform... and under one
look-and-feel... if the user (you) never changes your OSs default font
size... you get the idea.
The best way though is to accept that JPanel *needs* to change size and
work with it.
Hint: you can use setSize on higher level components to set the minimum
size on a top level frame (that's what it does by default). This works
for java.awt.Window and derived classes like JFrame. Call setSize after
pack() or revalidate().
This helps if you have very simple window with only a couple of small
components, and you want to keep it from getting scrunched down to
something unusable, but you still need to allow it to expand if needed.
setSize only works this way if called on your top level frame, not the
for example the JPanel.
<http://java.sun.com/javase/6/docs/api/java/awt/Window.html#setSize(int,%20int)>
Note that setSize is overridden for Window, and it won't set the size to
less than the predetermined minimum.