简体   繁体   中英

Swing custon JComponent size

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM