Changing preferred size of a Swing component

时光怂恿深爱的人放手 提交于 2019-12-12 18:05:54

问题


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 ?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/12549571/changing-preferred-size-of-a-swing-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!