Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to setColor(Variable)

 
James Hambrick
Ranch Hand
Posts: 282
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is what I have and I was thinking that I can do away with the two ifs to determine color by using g.setColor(SetFontColor) where I use the variable to determine color. SetFontColor is a String and has the value of "Red" is I cilcked red and "Black" if I choose black. This code does not work, but i'm sure there's a way to do this.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This looks generally OK; what does it do wrong? Are you sure those are the exact values of the String (this is a case where I'd use named constants like 'public static final String RED = "Red";' to be sure all copies were the same) ? Are you sure the values of the line end coordinates are what you expect?
 
James Hambrick
Ranch Hand
Posts: 282
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry I meant that the code does not work when I put a variable name into setColor(variable). But as the code stands now it works.

Yea I'm sure of the values of SetFonrColor because this code sets the variable depending on whether the user clicked the Red button or the Black button.



I just thought the code was repetitive and I could reduce it by using a variable.
[ July 10, 2007: Message edited by: James Hambrick ]
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, if the variable "SetFontColor" were of type java.awt.Color instead of String, and you did something like

if ("Red".equals(action))
    SetFontColor = Color.red;

then in your paint method you could just say

g.setColor(SetFontColor);

A word to the wise: the convention is that Java variable names start with a lower case. Starting them with an upper case letter makes them look like class names, and will confuse people who try to read your code -- myself included. One gets used to seeing things done a certain way!
 
James Hambrick
Ranch Hand
Posts: 282
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the advice Ill do that!
 
James Hambrick
Ranch Hand
Posts: 282
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do I make setFontColor a type java.awt.Color???
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic