Skip to main content

Nimbus and Opacity

Posted by ljnelson on July 31, 2008 at 10:25 AM PDT

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:

final JTextComponent previewComponent = new JTextField();
previewComponent.setBorder(null);
previewComponent.setEditable(false);
previewComponent.setOpaque(false);

...and you have what looks like a JLabel but what behaves like a JTextField.

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.

Related Topics >>

Comments

Thanks, Karl; good to know.

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. Karl

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.

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, Laird

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.