Question

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 ?

Was it helpful?

Solution

Suggestions:

  • Use a class extends JPanel (or JComponent),
  • give it a getPreferredSize() method override where you return a Dimension with the parameters that you desire.
  • For instance if the diameter will be based on a BufferedImage, you could have something like:

getPreferredSize example:

public Dimension getPreferredSize() {
  if (myBuffImg != null) {
    return new Dimension(myBuffImg.getWidth(), myBuffImg.getHeight());
  } 
  // default return value
  return super.getPreferredSize();      
}

Edit
Regarding your comment:

how would you handle the case of the component's content image changing though? is it just a a case of triggering a re-layout in the surrounding container?

You'd give this class a setImage(Image image) method of course, and you could repaint() this panel from within this method. The method I suppose could call revalidate() 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 the setImage(...) method to suggest that the container revalidate itself.

OTHER TIPS

A lot will come down to your individual needs. When dealing with "image panes", I typically will call setPreferredSize and invalidate, repaint when the image changes.

Changing the layout should automatically trigger a invalidate, reprint request anyway.

But I agree with Hovercraft, you'll want to do this from your own customs panel.

Another approach would be to use something like CardLayout to handle changing between different content layout outs, rather the cleaning up a single panel and re-adding comports to it

I'd also have a look at the Scrollable

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top