Reputation: 973
I want to change the font color of a TLabel, based on the value that i got from an Integer.
var
i: Integer;
begin
ValueGenerator (i);
if i <= 14 then
begin
L1.Font.Color := clBlue;
end;
if i >= 15 then
begin
L1.Font.Color := clGreen;
end;
if i <= 29 then
begin
L1.Font.Color := clGreen;
end;
if i >= 30 then
begin
L1.Color := clYellow;
end;
if i <= 49 then
begin
L1.Color := clYellow;
end;
if i >= 50 then
begin
L1.Color := clRed;
end;
L1.Caption := IntToStr(i);
end;
The value output is from 0 to 100. What ever value I got, my TLabel is always on clGreen. What I did wrong here?
Upvotes: 0
Views: 278
Reputation: 19106
Instead of case
I would use in this case some stacked if .. then .. else
, so you do not have to take care for the whole range of each color, just for the maximum value
if i <= 14 then
L1.Color := clBlue
else if i <= 29 then
L1.Color := clGreen
else if i <= 49 then
L1.Color := clYellow
// can easily extended with
// else if i <= 79 then
// L1.Color := clMaroon
else
L1.Color := clRed;
Upvotes: 6
Reputation: 8680
your color will always be either blue or green based on your logic. you need to add the top condition:
if (i >= 15) and (i < 30) then
begin
L1.Font.Color := clGreen;
end;
and so on and so forth.
Upvotes: 0
Reputation: 391346
Your ranges overlap, the value 20 is both greater than 15 and less than 29, so it first sets one color, and then another, but none of them makes the rest of the code not execute. So First you set clGreen, and then later you have the case where i is less than 49, which will overwrite.
Here's how you probably want to write that code:
case i of
0..14: L1.Font.Color := clBlue;
15..29: L1.Font.Color := clGreen;
30..49: L1.Font.Color := clYellow;
50..100: L1.Font.Color := clRed;
end;
Upvotes: 7