Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Setting a color from a string  RSS feed

 
Ben Strange
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I've just been getting into Java this year. Basically, I'm having big problems setting the color of buttons from a String, here's my code:


...



If there is any kind person out there who can help me I will be most thankful and forever indebted to them, Cheers
 
Henry Wong
author
Sheriff
Posts: 22830
119
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The setBackground() method takes a Color object -- and not a string object that describes the color object.

Henry
 
Campbell Ritchie
Sheriff
Posts: 53734
127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch

Henry has told you you can't pass a String to the setXXXColor methods. You can create a Color[] array, and there are static ready-made colours in the Color class, or you can create your own with the Color constructor.
If you want to use Strings you would have to create a Map<String, Color> which is probably more than you were planning to do at this stage.

Please use the code button; I shall see if I can edit your post, then you can see how much better it looks. I shall move you to the Swing forum, where we usually discuss this sort of question.
 
Ben Strange
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah ha, an array of colors, I hadn't thought of that. I'll do it that way. Thanks very much Campbell Ritchie
 
Campbell Ritchie
Sheriff
Posts: 53734
127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome . . . but I was simply elaborating Henry's suggestions.
 
Paul Clapham
Sheriff
Posts: 22185
38
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wouldn't get myself into a situation where I had to accept a String which might be the name of a colour in the first place. If I wanted the user to select from a list of colours, I would display a list of colours and arrange it so that the result of choosing from that list was a Color object.

Or maybe I would just use a JColorChooser component.

So perhaps you might want to post the code which gets this String, and consider suggestions about how to modify it so it returns a Color?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!