tags:

views:

75

answers:

2

I want to create a custom JComponent (specifically a custom JToggleButton) that has a custom appearance. What i want to do is simply override the default painting of the component and draw something of my own (an image for instance)

This is NOT a question on how to do that (I am fairly proficient with Java2D). What i want to ask is what steps must i take to ensure that my component has the size i desire it to have?

The tests i have done so far have been problematic. I draw an image of lets say 200*100 pixels and the layout managers display only a part of my component. I tried setSize, setPrefferedSize, setMinimumSize and none of them worked.

+1  A: 

the size is determined by the LayoutManager. if you will use a null LayoutManager you will be able to force a specific size (and location). otherwise you can override getPreferedSize() which will be respected by some layout managers.

Omry
I did override getPrefferedSize, i also tried simply setting the prefered size and none of these methods worked. What is the "correct" method of setting the size of your component in Swing? how does the swing team do it?
Savvas Dalkitsis
as I said, getPreferredSize() is used by the LayoutManager. which may decide to ignore it.to fully control the size of your component, you need to use a particular layout manager for the container that contains the button (use null layout + setSize(w,h) to force specific size).
Omry
+2  A: 

There is no way in the Swing model to outright guarantee that you will be given a set amount of space - layout managers can and do ignore minimum and maximum sizes, though normally they only ignore one or the other.

If you have a fixed size component, you should override getMinimumSize, getPreferredSize and getMaximumSize to all return a dimension of that fixed size that you need. If you can scale to some extent adjust the minimum and maximum as required. Overriding the methods avoids some third party code calling the set*Size methods and overwriting your choices (layout managers will still call setSize to tell the component what size it was actually allocated which is normal). It also makes sure the sizes are set before the layout manager starts laying out the component.

If the size of your component can change after layout has occurred, you need to make sure you invalidate the component layout properly but avoid doing this if you can.

ajsutton