如何在 java 中定义可自定义的 RGB 背景颜色?

Posted

技术标签:

【中文标题】如何在 java 中定义可自定义的 RGB 背景颜色?【英文标题】:How do you define a customisable RGB background colour in java? 【发布时间】:2017-04-03 20:18:58 【问题描述】:

我是 java 新手,我已经在 Google 上搜索了一段时间的答案,但我找不到获得 RGB 背景颜色的方法,我只能找到如何从主颜色中设置背景颜色由 java 提供(例如,“Color.BLACK”)。我正在使用 JFrame。请帮忙。谢谢。这是我的后台代码。

    public void paintComponent(Graphics g)
        super.paintComponent(g);

        this.setBackground(Color.PINK); //My current background colour code but I am looking to use a customisable RGB one.

        g.setColor(Color.BLACK);
        g.fillRect(0, 0, 40, y);

        tm.start();
    

【问题讨论】:

上下文在这里会有很大帮助。请出示您当前相关的minimal reproducible example 代码,并说明您的代码、您的问题和您的疑问的详细信息。 你考虑过看看JavaDocs for Color吗?另外,不要打电话给setBackground,也不要在paintComponent 中启动你的Timer,这会设置一个永无止境的绘画周期,这会消耗你的CPU 周期。绘画应该描绘当前状态,它不应该影响它 【参考方案1】:

你可以改变

    this.setBackground(Color.PINK);

    this.setBackground(new Color());//Put RGB number in the empty parenthesis

【讨论】:

-facepalm- 我不敢相信我没有意识到这一点。【参考方案2】:

如果您指的是 Swing 组件(例如 JFrame、JPanel)中的背景颜色,则缺少上下文,它们具有 getBackground() 或 setBackground(Color) 方法。

JPanel panel = new JPanel();
Color yourColor = panel.getBackground();

Color在java中有很多方法可以返回颜色类型例如。

int rgbValue = yourColor.getRGB(); // Returns the RGB value representing the color in the default sRGB ColorModel.
// or specific red, green, blue color value
int red = yourColor.getRed();
int green = yourColor.getGreen();
int blue = yourColor.getBlue();

【讨论】:

以上是关于如何在 java 中定义可自定义的 RGB 背景颜色?的主要内容,如果未能解决你的问题,请参考以下文章