Re: Making a grid with FG/BG setable colors

Posted by webmaster Guido on July 01, 2006

In Reply to Making a grid with FG/BG setable colors posted by Lee Hallin P12462 on June 29, 2006

I'm making something like a multiplication table where you have, say, 9 rows and 9 columns. I want to be able to set the foreground and backgroud colors independently in each of the 81 positions.

I was thinking of using "label"s but the foreground/text color selection isn't what I'd like.

Is there a way to make this "table" an array of "labels" (or somethings) so I can programatically manipulate the caption and/or colors in a loop rather than having different names for each of them (label1, label2...)?

You could use a Delphi StringGrid component with 9 rows and 9 columns. Or else, simply use 81 labels (or panels or other components that can display a text).

1. With a StringGrid

Add a stringgrid to the form, with the desired number of rows and columns. If you don't want a fixed row for headers, or a fixed column, set these properties in the Object Inspector.

At design time, set up two arrays that contain the foreground/background colours of each stringgrid cell. At program start, fill the arrays with default colour combinations. For example:

for Row := 0 to ... do begin
  for Col := 0 to ... do begin
    aColorFG[Row, Col] := clBlack;
    aColorBG[Row, Col] := clWhite;

Add an event-handler that displays each cell of the stringgrid in the desired colour. The colours are obtained from the colour-arrays above.

2. With labels

It's quite a tedious job to manually set up 81 labels at design time. And modifying the design later on to 100 labels would be a nightmare... So, it's best to create the labels at runtime, for example with a procedure called "CreateLabels". For each label that is created, add a pointer to a "component-array".

That way, you can access the labels in your program code with their row/column coordinates, instead of using their names.

Note that in this case, you don't need the colour-arrays, because the colours are saved within the label-components.

Next: write a routine that sets the colours of a stringgrid cell or of a label, based on its coordinates. Example:

procedure SetColours(Row, Col: integer; FG, BG: TColor);

And finally, if you opted for using labels or panels, write a routine that sets the caption (text) of a component based on it's row/column coordinates in the component-array. Example:

procedure SetLabelCaption(Row, Column: integer; S: string);

So, what do you prefer: stringgrid, labels, panels, anything else? Based on your choice, I'll brew some real code :)

Related Articles and Replies





DelphiLand Club members: enter your Membership password.
Guests can get a Forum Guest password by subscribing to the DelphiLand Newsletter.