简体   繁体   English

在Swing中获取当前外观组件背景颜色的正确方法是什么?

[英]What is the proper way to get the current look-and-feel's component background color in Swing?

I am writing a custom Swing component with my own painting. 我正在用自己的绘画编写一个自定义Swing组件。 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. 我很难在Google上找到它。 Anyone know? 谁知道? Thanks! 谢谢!

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
    }
}

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. 我猜一般来说LAF的背景颜色是由JPanel决定的,所以我猜你的自定义组件只能扩展JPanel,你不必担心这个问题。

If you want to query the default backgroud colors of every component then you can use the UIManager to look it up. 如果要查询每个组件的默认背景颜色,则可以使用UIManager查找它。 See the UIManager Defaults example. 请参阅UIManager Defaults示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM