setBackground(new color()); in java does not understand the given RGB value

90,562

Solution 1

I have a program with some gui, on the JFrame I set,

 setBackground( new Color(107, 106, 104) );

[The problem] It gives a greyish color, but not the right one! 
If I check the gui's color in Photo Shop, it gives me the RGB 
values (126, 125, 123)

you can not set setBackground for JFrame, this is only possible for ContentPane, for example

JFrame#getContentPane.setBackground(new Color(107, 106, 104));

EDIT

enter image description here

from code

import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Check extends JFrame {

    private static final long serialVersionUID = 1L;

    public void makeUI() {
        JFrame f = new JFrame();
        f.getContentPane().setBackground(new Color(107, 106, 104));
        f.setDefaultCloseOperation(EXIT_ON_CLOSE);
        f.setSize(new Dimension(300, 200));
        f.setVisible(true);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Check().makeUI();
            }
        });
    }
}

Solution 2

check with Adam's comment and even if not worked then without any working code I am just guessing that this scenario is getting raised due zero ordering or saying layout of the JFrame. Actually in java swing , setting the background color needs a little bit of more attention, check Swing Java Docs.

Share:
90,562
JW_
Author by

JW_

Updated on July 22, 2022

Comments

  • JW_
    JW_ almost 2 years

    I have a program with some gui, on the JFrame I set,

     setBackground( new Color(107, 106, 104) );
    

    The issue is that I get a greyish color, but not the right one. If I check it in PhotoShop, it gives me the RGB values (126, 125, 123)

    Ps. I have tried with HEX value, the same result.

  • JW_
    JW_ over 12 years
    It is in the constructor of a class that extends JFrame?
  • JW_
    JW_ over 12 years
    mKorbel, I have tested your code, it works like a charm. But the way i'am doing it, it won't work and I can't see why.
  • mKorbel
    mKorbel over 12 years
    @JW_ this is reason why we asking for SSCCE, nobody knows what ... :-)
  • trashgod
    trashgod over 12 years
    @mKorbel's result verified using Zoom. I suspect an errant composite mode.
  • JW_
    JW_ over 12 years
    It's the right answer that getContentPane() needs to be called on the setBackground()
  • Spoody
    Spoody over 6 years
    Don't post code only, add an explanation so that readers can better understand your answer
  • clearlight
    clearlight about 5 years
    Please con't post code-only answers. You need to explain what your code does/how it fixes the problem. Even if you think it's good enough for this one question, the site requires keeping a certain minimal standard of commentary, and there are reasons for it.