views:

36

answers:

2

I'm creating a custom Swing component that inherits from JPanel.

What is the right way to override/implement the various sizing methods (getPreferredSize, setPreferredSize, getMinimumSize etc.) in order to get "good behaviour", particularly with regards to:

  • Working with different layout managers
  • Behaving correctly when setPreferredSize() is called
  • Reacting appropriately when a border is set via setBorder()
+1  A: 

Don't inherit from JPanel unless your component is a composite of several subcomponents. In most cases inheriting from JComponent is enough.

As far as resizing goes... override getPreferredSize, getMinimumSize and getMaximumSize methods to get an appropriate behavior in layout managers.

If your component is a composite of subcomponents in most cases preferred size is already defined by combination of your subcomponents so you don't have to override this one.

eugener
Thanks! Looks like I can directly inherit from JComponent in some cases, in other cases I do have a composite so need JPanel. Are there any guidelines on how to implement getPrefferedSize, getMinimumSize etc? Main reason is that the interaction between these and setPreferredSize, setBorder etc. seems potentially very complex.....
mikera
This is what JComponent API sais: "If the preferredSize has been set to a non-null value just returns it. If the UI delegate's getPreferredSize method returns a non null value then return that; otherwise defer to the component's layout manager". But IMO that depends on LAF very much. so I would suggest implementing sizes in your UI delegates an then delegate to UI delegates :) As far as borders go, all 3 sizes should include border size , so you shouldn't worry about it.
eugener
Here is a very good article about custom components written by Kirrill: http://today.java.net/article/2007/02/19/how-write-custom-swing-component
eugener
A: 

Although rather annoying: that depends, on the layoutmanager in this case. Usually the layoutmanager can best be used along with constaints to get a good layout. I've used GridBagLayout, and after getting used to it, I found it worked pretty well using right GridBagConstraint for each component. Sometimes a good visual ui designer can help too, like the one from Netbeans, or you could consider a paid one like Swing Designer or JFormDesigner. Can save you some time fiddling with pixels.

Gerbrand
Cool, thanks for the info! I've also found MigLayout to be very useful in this reagrd.....
mikera