java添加组件不显示不出来,使用Swing组件作为内容的自定义Java工具提示不会显示...

在Swing中尝试创建一个组件提示框以展示多张图片,但遇到提示框大小被忽略,只显示一个小点的问题。解决办法是注意到JToolTip并非设计为容器,而需要通过覆盖getPreferredSize()方法来使其行为类似容器,以适应包含多个组件的需求。不要使用setXXSize或定制UI,而是让组件根据布局管理器自动计算尺寸。
摘要由CSDN通过智能技术生成

I'm trying to show multiple images in a component's tooltip, found createToolTip() and implemented a custom that adds the needed components like this:

setComponent(component);

JPanel images = new JPanel(null);

images.setLayout(new BoxLayout(images, BoxLayout.X_AXIS));

for(ImageIcon icon:myIcons) {

images.add(new JLabel(icon));

}

JPanel content = new JPanel(new BorderLayout());

content.add(new JLabel(title), BorderLayout.NORTH);

content.add(new JLabel(description));

content.add(images, BorderLayout.SOUTH);

add(content);

However, all I see is a little dot, indicating that the tool tip is shown, but somehow the size is ignored. What do I miss implementing a custom tooltip?

解决方案

The base "problems" are that JToolTip

is-not designed as a container, it's only accidentally a container because JComponent is. For a Swing "not-container" its the responsibility of the ui-delegate to act as LayoutManager.

isn't rich enough, it can handle text-only (at least with the emergency door html, which is @Andrew's favourite :-)

By-passing those limitations basically is a driving that widget nearly over the edge. A clean solution would roll a new component .. On the other hand, the OP already found the screws to tweak. The only thingy that could be slightly improved is to neither call setXXSize, nor set a custom ui. Instead, make it behave like a container by overriding getXXSize() like:

@Override

public Dimension getPreferredSize() {

if (getLayout() != null) {

return getLayout().preferredLayoutSize(this);

}

return super.getPreferredSize();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值