简体   繁体   English

Java Swing - 为所有子组件设置不透明度?

[英]Java Swing - set opacity for all children components?

I've got some Swing components with children. 我有一些带孩子的Swing组件。 When I setOpaque(false) on the parent, the children still have opacity. 当我在父级上使用setOpaque(false)时,子级仍然具有不透明度。

So I hacked up this function (thanks SOF users): 所以我破解了这个功能(感谢SOF用户):

Component[] comps = this.getComponents();

for(Component c : comps) { if(c instanceof JComponent) {
    ((JComponent)c).setOpaque(false); }
}

But now I'm plagued with self-doubt - this seems sort of clunky, is there a better way to do it? 但现在我被自我怀疑所困扰 - 这看起来有点笨拙,有没有更好的方法呢?

You could add a ContainerListener to the panel and the set the opacity of the children as they are added. 您可以向面板添加ContainerListener,并在添加子项时设置子项的不透明度。

However neither this solution or yours will handle nested panels. 但是,此解决方案或您的解决方案都不会处理嵌套面板。

There is no easy solution that I'm aware of. 我不知道有什么简单的解决方案。

Your way is OK. 你的方式还可以。 A little bit better is: 好一点是:

public void setOpaqueForAll(JComponent aComponent, boolean isOpaque) {
  aComponent.setOpaque(isOpaque);
  Component[] comps = aComponent.getComponents();
  for (Component c : comps) {
    if (c instanceof JComponent) {
      setOpaqueForAll((JComponent) c, isOpaque);
    }
  }
}

But you need to call this method each time if your component tree changed. 但是,如果组件树发生更改,则每次都需要调用此方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM