HiveBrain v1.2.0
Get Started
← Back to all entries
patternModerate

Make it easier with color changing

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withcolormakechangingeasier

Problem

How can I simplify this in Delphi?

Procedure colori1
Begin

 if Temperatura=16) and (Temperatura=19) and (Temperatura=23) and (Temperatura=27) and (Temperatura=30 then
 begin
  Form1.Label1.Font.Color:=clRed;
  Form1.Label2.Font.Color:=clRed;
  Form1.Label3.Font.Color:=clRed;
  Form1.Label4.Font.Color:=clRed;
  Form1.Label5.Font.Color:=clRed;
 end;
end;


If I use "for cycle" like this:

For i:=0 to n do label[i].font.color:=clRed


I'll obviously get an error, because Delphi doesn't know what label[i] means. Any suggestions?

Solution

Declare a local variable to hold the color:

var
  Color: TColor;


Then decide what the color should be:

if Temperatura<=15 then
  Color:=clBlue;
else if Temperatura<=18 then
  Color:=clAqua;
else ...


Then assign the color to the controls:

Form1.Label1.Font.Color:=Color;
Form1.Label2.Font.Color:=Color;
....


The labels could be stored in an array or a list. So that you can iterate over them to assign the color. You could declare the array like this, in the form class:

FLabels: TArray;


In the constructor assign it like this:

FLabels := TArray.Create(Label1, Label2, Label3, Label4, Label5);


To iterate over it setting the color do this:

var
  lbl: Tlabel;
....
for lbl in FLabels do
  lbl.Font.Color:=Color;


You appear to be using a global variable Form1. Your code will be better without that global variable, and having this procedure (and others like it) converted into a method of the form.

Code Snippets

var
  Color: TColor;
if Temperatura<=15 then
  Color:=clBlue;
else if Temperatura<=18 then
  Color:=clAqua;
else ...
Form1.Label1.Font.Color:=Color;
Form1.Label2.Font.Color:=Color;
....
FLabels: TArray<TLabel>;
FLabels := TArray<TLabel>.Create(Label1, Label2, Label3, Label4, Label5);

Context

StackExchange Code Review Q#39763, answer score: 12

Revisions (0)

No revisions yet.