Swing custon JComponent size
I want to create a custom JComponent (especially a custom JToggleButton) that has its own look and feel. What I want to do is just override the default component image and draw something of my own (like an image)
This is NOT a question of how to do this (I'm pretty good with Java2D). What I want to ask is, what steps should I take to ensure that my component is the size I want it to be?
The tests I've done so far have been problematic. I am drawing a let say image of 200 * 100px and layout managers only render part of my component. I tried setSize, setPrefferedSize, setMinimumSize and none of them worked.
source to share
There is no way in the Swing model to guarantee that you are given a certain amount of space. Layout managers can ignore minimum and maximum sizes, although they usually only ignore one or the other.
If you have a component with a fixed size, you must override getMinimumSize
, getPreferredSize
and getMaximumSize
to all the returned dimension of fixed size that you need. If you can scale the min and max values ββto some extent as needed. Method overriding avoids some third party code calling methods set*Size
and overwriting your options (layout managers will still call setSize
to tell the component what size was actually allocated, which is normal). It also ensures that the dimensions are set before the layout manager starts composing the component.
If your component can resize after the layout has occurred, you need to make sure you mis-assign the component's layout, but don't if you can.
source to share