0

I am creating small application where user will select color by pressing button. I would like to when user selects the color from JColorChooser dialog and setup the color of application as background also to put name of the color in jLabel.

So far I have create following code:

private void btnChooseColorActionPerformed(java.awt.event.ActionEvent evt) {                                               
    Color color = JColorChooser.showDialog(getContentPane(), "Choose color", Color.yellow);
    this.getContentPane().setBackground(color);
    lblColorSelected.setText("Color: " + /* here I would like to append code that will display name of the color what user have selected */);
} 

I have successfully created that user selects the color from dialog and color goes on application as background but only problem is that I don't know how to get the name of the colors selected by the user. Do you have any idea?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Denis
  • 11
  • 4
  • 2
    "Color" doesn't have a "name" per say, but instead has properties (RGB). You could use something like [this](http://stackoverflow.com/questions/3607858/how-to-convert-a-rgb-color-value-to-an-hexadecimal-value-in-java) to generate a hex representation of the color, which is very common (used a lot in the web) – MadProgrammer Jan 12 '16 at 22:24
  • Thanks @MadProgrammer for suggestion, but I would need to present the name of color on label. – Denis Jan 12 '16 at 22:40
  • 1
    As I said "color" doesn't have a "name", the best you can do is present the RGB properties in a form which is most commonly used, which is generally the hex value – MadProgrammer Jan 12 '16 at 22:48
  • Another option would be to generate some ranges from RGB and display it the name of color accordingly – Frakcool Jan 12 '16 at 23:23
  • 2
    With 256 levels of R, G & B, there are 16,777,216 colors. Do you really expect humans to have named them all with an unique name? By following @MadProgrammer's advice we can uniquely identify them all. Apart from that I'd recommend showing the user a square label that uses that color. – Andrew Thompson Jan 13 '16 at 20:56
  • Possible duplicate of [Java color code convert to color name](http://stackoverflow.com/questions/4126029/java-color-code-convert-to-color-name) – user1803551 Jan 13 '16 at 21:03

1 Answers1

0

Assuming that there is a limited number of possible colors (for example, you only allow red, green, and blue), it might be easiest to simply use a switch statement or a brute-force if else statement to assign the names.

String colorName = new String(); 

//My syntax may be off here but you get the idea
if Color.color.equals(c)
{
    colorName = color;
}

If you allow any color to be selected, then MadProgrammer is right. This will let you display the hex values as a string.

Community
  • 1
  • 1
Scott Forsythe
  • 360
  • 6
  • 18