更改Swing组件的首选大小 [英] Changing preferred size of a Swing component

查看:187
本文介绍了更改Swing组件的首选大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个swing组件,该组件的理想大小将根据当前显示的内容(在这种情况下为图像)变化.

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).

我希望在更改内容时可以更改此首选大小,并且还希望更改布局(例如,如果组件在JScrollPane中使用,则滚动范围将更改为适合的大小).组件).

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).

在Swing中执行此操作的规范方法是什么?

What is the canonical way to do this in Swing ?

推荐答案

建议:

  • 使用类扩展JPanel(或JComponent),
  • 为其提供getPreferredSize()方法覆盖,在其中您将返回具有所需参数的Dimension.
  • 例如,如果直径基于BufferedImage,则可能具有以下内容:
  • 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示例:

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?

您当然可以给该类一个setImage(Image image)方法,您可以在此方法内repaint()此面板.我猜想的方法可以在此JPanel的祖先上调用revalidate(),从而导致该组件的布局重新布局,但是我不太担心此类中的方法对其祖先有副作用,并且认为这样做可能会更好调用setImage(...)方法的代码建议容器重新验证自身.

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.

这篇关于更改Swing组件的首选大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆