开发者

Java Swing - set opacity for all children components?

开发者 https://www.devze.com 2023-04-09 16:56 出处:网络
I\'ve got some Swing components with children.When I setOpaque(false) on the parent, the children still have opacity.

I've got some Swing components with children. When I setOpaque(false) on the parent, the children still have opacity.

So I hacked up this function (thanks SOF users):

Component[] comps = this.getComponents();

for(Component c : comps) { if(c instanceof JComponent) {
    ((JComponent)c).setOpaque(开发者_如何学JAVAfalse); }
}

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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号