I am writing a custom Swing component with my own painting. I'd like to query whether or not the current look and feel's components are opaque, and if so, what their background color is so my component can use it too. I'm having a hard time finding that on Google. Anyone know? Thanks!
views:
46answers:
2
A:
That's pretty simple:
public class MyComponent extends JComponent {
public void paintComponent(Graphics g) {
if (this.isOpaque()) {
// Paint background
g.setColor(this.getBackground());
g.fillRect(0,0,this.getWidth(), this.getHeight());
}
g.setColor(this.getForeground());
// Continue painting
}
}
Elie
2010-04-26 00:23:02
Hmm... that is simple. I thought I tried that ;) Let me double check when I get home and get back to ya. That is how my class was set up (extends JComponent). I was doing the painting in paint before the call to super.paint.
John B.
2010-04-26 18:19:43
Well, I must have been messing with the opacity or something when I tried that and forgot to set it back ;) That seems to have done it. Thanks!
John B.
2010-04-27 02:23:27
A:
Don't really understand the question. Each component can have a different background color so what background color do you want your custom component to use?
I would guess generally speaking the background color of a LAF would be determined by a JPanel, so I guess your custom component could just extend JPanel and you don't have to worry about this.
If you want to query the default backgroud colors of every component then you can use the UIManager to look it up. See the UIManager Defaults example.
camickr
2010-04-26 03:51:21
There appears to be a default background color for most standard components in a given Look and Feel. On my system it's natively some sort of gray. I think you assumed correctly from the sound of it. I might try the JPanel. Right now I'm extending JComponent because it seemed right.I was looking at the UIDefaults and/or UIManager "getColor(Object key)" methods but I'm not sure what to pass in as the key. Maybe you can point me in the right direction? Thanks for the input.
John B.
2010-04-26 18:18:14