tags:

views:

46

answers:

2

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!

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
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.
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.
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
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.
Did you look at the link I gave you? It has all the key values.
camickr
Oh I see, the program lists them. Gotcha. Thanks!
John B.