It's not a secret anymore!
The moose likes Swing / AWT / SWT and the fly likes Difference between setOpaque() and setVisible() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Difference between setOpaque() and setVisible()" Watch "Difference between setOpaque() and setVisible()" New topic

Difference between setOpaque() and setVisible()

Ken Austin
Ranch Hand

Joined: Aug 20, 2012
Posts: 39

Good morning, all. I am still working through a beginner textbook, and I have a quick question for you...

Can someone explain the difference between setVisible() and setOpaque()?

The API docs say this about setVisible()
Makes the component visible or invisible. Overrides Component.setVisible.

The API docs say this about setOpaque()
If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.

Why is there a need for setOpaque()?


(edited for grammar)
m Korbel
Ranch Hand

Joined: Jun 19, 2012
Posts: 174
- (J)Components#setVisible() is method for to show or hide (J)Component in the AWT / Swing GUI

- (J)Components#setOpaque() is method for to set transparency for (J)Component,

1. for example JLabel, JViewport, GlassPane are opaque

2. you can pass AlphaComposite (new Color (int, int, int, AlphaComposite)) as transparency parameter for (J)Components

3. notice Transparency by using setOpaque(boolean b) or AlphaComposite is diferrent with compare with Java Translucency

- there are a few code example on this Forum, Oracle tutorial, (notice examples for Graphics(2D) are in most cases outdated, have to change method paint() to the paintComponent or paintChildren)
Kemal Sokolovic

Joined: Jun 19, 2010
Posts: 825

If a component is opaque, it's obligated to paint its background completely. Opacity for a given component in Swing indicates whether or not the content behind a given component is visible to the user. E.g. JButton is typically opaque because it completely "hides" whatever happens behind it. On the other hand, if you want to have a rounded button of your own, you need to make sure it is not opaque because there are things behind its bounds that should be visible. I think all Swing components are opaque by default except for JLabel.

The quieter you are, the more you are able to hear.
I agree. Here's the link:
subject: Difference between setOpaque() and setVisible()
It's not a secret anymore!