I have a swing component where the ideal size of the component will vary based on the content that is is currently being displayed (which happens in this case to be an image).
I’d like this preferred size to change when the content is changed, and also allow the layout to be changed (for example, if the component is being used inside a JScrollPane then the scroll extents would change to fit the size of the component).
What is the canonical way to do this in Swing ?
Suggestions:
getPreferredSize()method override where you return a Dimension with the parameters that you desire.getPreferredSize example:
Edit
Regarding your comment:
You’d give this class a
setImage(Image image)method of course, and you couldrepaint()this panel from within this method. The method I suppose could callrevalidate()on this JPanel’s ancestor causing this component to be re-layed out, but I’m not too crazy about methods in this class having side effects on its ancestor and think that likely it will be better for the code calling thesetImage(...)method to suggest that the container revalidate itself.