Nimbus and Opacity
This one tripped me up, and I thought I'd post it here. I have a case where I need to pour text into a JTextField, but have that JTextField look like a JLabel. So as I type in one field, I need this "gray" second field to update, live, before the user's eyes. I also need the ability for the user to cut-and-paste values out of it. This sort of thing is reasonably common in properties panels and the like.
Now, normally all you have to do is something like this:
...and you have what looks like a JLabel but what behaves like a JTextField.final JTextComponent previewComponent = new JTextField(); previewComponent.setBorder(null); previewComponent.setEditable(false); previewComponent.setOpaque(false);
Well, except under Nimbus, where the setOpaque(false) seems to have no effect. Turns out you need to also set the background color to a transparent color as well. Fortunately, this combination of behaviors seems to work under all the other look and feels (looks and feels?):
previewComponent.setBorder(null); previewComponent.setEditable(false); previewComponent.setOpaque(false); previewComponent.setBackground(new Color(0, 0, 0, 0));
I hope this helps other Swing folks out.
- Login or register to post comments
- Printer-friendly version
- ljnelson's blog
- 1137 reads






Comments
by ljnelson - 2008-08-01 09:26
Thanks, Karl; good to know.by kschaefe - 2008-08-01 08:33
It is a feature. The overloaded and poorly understood "opaque" property was never meant to be the "no background" property. The behavior is correct; however, since the previous incorrect behavior existed for so long, some might argue that is still not the right thing. Karlby pcox - 2008-08-01 08:26
Thanks for the clarification, it explains why things looked a little haywire under Nimbus when compared to Metal or Windows. It sounds like it involves a bit more work than simply dropping a new jar in and changing the loaded L&F. That's progress! :) Thanks, Pete.by ljnelson - 2008-08-01 07:08
I'm not sure whether it's a bug or a feature, but Jasper Potts had this to say (from http://forums.java.net/jive/thread.jspa?messageID=267839): "To solve the case of when you want to make a component transparent we added a fix in 6u10 b26 or b27 so if you set the background color to a color with a alpha value of 0." That tells me *he* thinks it's a feature. The reason I put this blog entry together was because the sequence of calls I detail works under all look and feels (well, the Sun-supplied ones anyhow). Cheers, Lairdby pcox - 2008-08-01 01:58
So is this a bug or a feature? Unless the L&F team for 6u10 have some justifiable reason for this, it pains me that one has to code look and feel specific workarounds.