Difference between revisions of "Howdy World (Hello World on steroids)"

From Lazarus wiki
Jump to navigationJump to search
Line 379: Line 379:
 
===What was the second number?===
 
===What was the second number?===
 
Add variable SecondNumber to the form's private section (the same as FirstNumber) and make it a longint as well.
 
Add variable SecondNumber to the form's private section (the same as FirstNumber) and make it a longint as well.
 +
 +
== What's on your mind==

Revision as of 21:15, 8 June 2011

Template:newpage This Wiki chapter is a tutorial for Lazarus. It explains the first steps to get a working piece of software and explains some of the best practices along the way. The end result is twofold (hopefully): the reader understands the basic concepts to build software with Lazarus and she has an actual piece of working software that can be embedded in other programs: a calculator. A calculator is fairly easy to implement and everyone understands it’s concepts. So no need to describe a lengthy business case beforehand. The calculator is limited to integer calculations, but can easily be extended. This tutorial does not describe the installation process of Lazarus. It is assumed that Lazarus is installed and ready for use (preferably the latest, stable version which at the moment of writing is Lazarus 0.9.30 with Freepascal v2.4.2). This tutorial is more or less platform independent (but targeted at thick clients). All screenshots were made on a Windows XP PC; hence the blue/red/grayish color scheme.

Let’s get started

It’s best to create a separate directory for every new project. So before getting our feet wet, let’s create a directory to save our Calculator project in (do this with your OS application of choice). This directory will be the root for all files created for the project.

  • Create a new directory for the demo project (let’s call it $HOME/CalculatorDemo).

(Text that describes actions that must be executed is bulleted like the previous line.)

With this out of the way it’s time to start a new Lazarus project.

  • Start Lazarus.
  • From the menu choose Project/New Project…
  • In the dialog that is presented select Application and press OK (if the IDE complains about unsaved changes, press No).

To make sure that all files of our new project end up in the right directory the project must be saved first.

  • From the menu choose File/Save All.
  • Select the directory that was created previously ($HOME/CalculatorDemo).
  • Enter a new project name: CalculatorDemo
  • Press Save (or whatever is the Save button in your own language)
  • The IDE wants to save the main form as well: enter ’’ufrmMain’’ as the forms unit name.
  • The IDE asks if the filename should be changed to a lowercase name. Confirm this by pressing the button ‘Rename to lowercase’.

In theory the program that is thus created is a piece of valid software that can be executed. Before compiling it for the first time, two changes are recommended: assigning new locations (directories) for the compiled units and target filename.

  • From the menu choose Project/Project Options…
  • Select Compiler Options/Paths (click on the node in the treeview)
  • Put the text ‘‘bin\’‘ before the target filename (or ‘‘bin/’‘ for a *nix environment)
  • Also note the ‘‘lib’‘ prefix for the ‘unit output directory’ (don’t change it).
  • Press OK

The image below is how this would look like on a Windows machine. tutcal project options.png

By doing this the project folder will not be cluttered with output that is generated by the compiler. The files in the project folder are required to (re-) build the program. Everything in the ’’lib’’ and ’’bin’’ directories can be deleted when archiving the project.

Now as a first test the project can be compiled and run.

  • Press F9 (the shortcut for compile, build and run the program)

If all went well a blank window is displayed. Now we know that a solid basis is created on which we can start building the program.

  • End the running program by clicking on the Close icon (this depends on the OS).

The first component

Lazarus has a so called ‘component palette’:

tutcal component palette.png

All components that are available to build a user interface are logically grouped on the component tabs. The actual number of tabs depends on the installed packages. But the basic palette looks something like the above image. The first tab is Standard, followed by Additional, Common Controls etc. To retrieve the type name of a component, hover with the mouse pointer above the component icon and a hint is displayed that gives the type name (to be more precise: the class type of the component is displayed). For an explanation of all controls look at this Lazarus introduction

The first thing that needs to be done for the Calculator program is to create a display area where the entered numbers are, well, displayed. For this a TEdit control is used.

# Note: the visual components are referred to as Controls. For now the difference between a 'component' and a 'control' is not that relevant. 

To place a control on the form, the form must have the focus. Pressing F12 on the keyboard changes the focus from the form editor to the source code editor and vice versa.

  • Press F12 once or twice to get the form window on top (see image below).

tutcal form on top.png

  • Select the Standard tab on the component palette. This is the tab that is selected by default.
  • Click on the TEdit component (hover above the component icons to get the class type names).
  • Click somewhere in the middle of the form. This places a TEdit control on the form that has a name that is the same as the control’s type without the capital 'T' and with a number at the end (e.g. Edit1). When a second TEdit control were to be placed on the form it would be named Edit2. And so forth. This applies to all components.

Now that the control is placed on the form it can be customized to our needs. This customization takes place in the Object Inspector. That is the window at the left side of the screen with the list of properties for the TEdit control that are customizable. tutcal object inspector.png

Properties determine the look and feel and behavior of a control. It’s easy to change a property: just click on one of them, enter a new value and press Enter. The effects on the control are instantly visible. The properties in the Object Inspector are all the properties for one control. In particular the control that has the focus/is selected. The control that is selected can be recognized by the small black squares that surround the control. So the way to change properties of a control is by first selecting it and then make the changes in the Object Inspector. If no control is selected, the form properties are displayed.

Make the following changes to the properties of Edit1.

  • change Name to edDisplay.
  • change Align to alTop (change Align, not Alignment!).
  • change Alignment to alRightJustify (change Alignment, not Align).
  • change BorderSpacing.Around to 6.
  • change Text to 0 (the number zero, not the letter oh).

These properties are pretty self-explanatory. Especially when the above changes are made and the effect is monitored on the form.

As a finishing touch the Font that is used to display texts on all controls will be changed. The font can be changed in two places: the font property of edDisplay or the form’s font property. Changing the font for the form itself has the benefit that all newly placed controls on the form will 'inherit' the new font. So that is where we are going to make the change.

  • Click somewhere in the middle of the form. This deselects the edDisplay control and selects the form itself. The form’s properties are now displayed in the Object Inspector.
  • In the Object Inspector click on the Font property. The Font line is now highlighted and a button with three dots is displayed.
  • Click on the button with the three dots. This opens the Font dialog.
  • Select Verdana, Bold, Size 10.
  • Press OK.

The Form’s title is not very meaningful. The default text 'Form1' is displayed.

  • In the Object Inspector click on the Caption property.
  • Change the caption text to Calculator Demo.

The result of all these actions is a form that looks something like this: tutcal form with tedit.png

Now is a good time to save the form.

  • Select from the menu File/Save or press the key combination Ctrl-S.

Remember to save and save often!

Buttons

What use is a calculator if numbers cannot be entered? So the next step is adding buttons for the digits 0..9. Before placing the buttons for the digits, a so called container is placed on the form. A container defines an area on a form where controls can be grouped together. The form is a container. A TPanel is another container that can be placed on a form. Containers can be placed inside other containers, but that’s for another tutorial.

  • On the component palette, select the TPanel control.
  • Click on the form to place the panel.

A new panel is now visible on the form with a default width, height and caption. Note that the font for the panel caption is inherited from the form. This panel will be used to group all buttons, so a number of properties must be changed.

  • Remove the text Panel1 from the caption property.
  • Change Align to alClient.
  • change Borderspacing.Around to 6.
  • increase the form’s Width to 300 (first click on Form1 in the Object Inspector treeview).
  • increase the form’s Height to 350.

(Increasing the size of the form gives us some space to move controls around.)

Now the digit buttons will be added.

  • On the component palette, select the TButton control.
  • Click on the form, somewhere in the middle, to place the button. The button is placed on the panel. this is visible in the Object Inspector treeview: Button1 is a so called child of Panel1. This effectively means that when Panel1 is moved, all child controls move with it. And when Panel1 is deleted, all child controls are deleted as well.
  • In the Object Inspector change Caption to 0
  • Change Width to 32.
  • Change Height to 30 .
  • Change Name to btnDigit0.

This must be repeated for the digits 1..9. The quickest way to do this is by copy/pasting the 0-button.

  • Right click on the button created above and select Copy from the pop up menu.
  • Right click somewhere else on Panel1 and select Paste; a second button is added to the panel. The only difference with the first button is the name btnDigit1.
  • change the Caption property in the Object Inspector to 1
  • repeat the Paste action 8 more times for the remaining buttons.
  • Move the buttons around on the form to get a lay out that looks like a calculator:

tutcal calculator digits.png

Next are the four buttons for the mathematical functions (add, subtract etc.).

  • Drop a new TButton on the panel.
  • Change Width to 32.
  • Change Height to 30 .
  • Change Caption to +
  • Change Name to btnFunction.
  • Copy/paste this button 3 more times, changing the caption to -, * and /.
  • Align the buttons vertically, right next to the digit buttons

And the 'special' buttons:

  • Copy/Paste the + button.
  • Change Caption to +/-.
  • Change Name to btnPlusMinus .
  • Position the button just below button 3.
  • Copy/Paste the + button.
  • Change Caption to C.
  • Change Name to btnClear.
  • Position the button to the right of button +.
  • Copy/Paste the + button.
  • Change Caption to =.
  • Change Name to btnCalculate .
  • Position the button to the right of button /

Not what all buttons are placed, resize the form to fit the buttons tightly.

It should look something like this:

tutcal calculator gui ready.png

Remember to save and save often!

Responding to events

A gui application (often) is an event based application. This means that the application does nothing until we tell it to do something. For example by entering data via the keyboard, pressing buttons etc. One of the things the calculator needs to do is responding to mouse clicks on the buttons 0..9. This is where the IDE helps us. Adding a so called event handler for a button is easy.

  • Make sure the form with all buttons is visible (if necessary press F12 once or twice).
  • Double click on the button with caption 0: the IDE automatically creates a procedure that will handle mouse clicks: procedure TForm1.btnDigit0Click(Sender: TObject);
  • type the following code between begin and end:

<Delphi>edDisplay.Text := edDisplay.Text + '0'</Delphi> edDisplay is an edit box. The way to change the contents of the edit box is by modifying the Text property. The above statement adds the number '0' to the text in the edit box and this is visible on screen immediately.

  • Double click on the button with caption 1.
  • type the following code between begin and end:

<Delphi>edDisplay.Text := edDisplay.Text + '1'</Delphi>

It's a good idea to compile the code from time to time to check for syntax errors.

  • Select from the menu: Run/Run (or press F9); the project is compiled and the application starts.
  • Click the digits 0 and 1 a couple of times and see what happens on screen. The other buttons do nothing obviously because the event handlers have not yet been added.
  • Stop the Calculator Demo program.

Of course it's now easy to add event handlers for the digits 2..9, but this will result in a lot of redundant code. Every event handler does exactly the same, only the digit is different. The way to remove this redundancy is by creating a procedure that does the processing, and add the variable data (the digits 0..9) as a parameter.

  • In the editor locate the lines where class TForm1 is declared. It will look something like this:

<Delphi> { TForm1 }

 TForm1 = class(TForm)
   btnDigit0: TButton;
   btnDigit1: TButton;
   btnDigit2: TButton;
   btnDigit3: TButton;
   btnDigit4: TButton;
   btnDigit5: TButton;
   btnDigit6: TButton;
   btnDigit7: TButton;
   btnDigit8: TButton;
   btnDigit9: TButton;
   btnFunction: TButton;
   btnFunction1: TButton;
   btnFunction2: TButton;
   btnFunction3: TButton;
   btnCalculate: TButton;
   btnPlusMinus: TButton;
   btnClear: TButton;
   edDisplay: TEdit;
   Panel1: TPanel;
   procedure btnDigit0Click(Sender: TObject);
   procedure btnDigit1Click(Sender: TObject);
 private
   { private declarations }
 public
   { public declarations }
 end; </Delphi>

Note that in the above class definition all controls and procedures are declared that we added to the form via 'pointing-and-clicking'. Do not make any manual changes in there!! The IDE will get nervous when you do. The place to add custom variables, procedures and functions is in the private or public sections. As a general rule all custom variables are added to the the private section. Procedures and functions are added to the private section as well, except when other forms need to call these procedures or functions (which shouldn't happen too often).

Back to our digits problem: we need a procedure that adds digits to the display, where the digits themselves can vary.

  • Add procedure AddDigit to the private section of the form.

<Delphi> private

   { private declarations }
   procedure AddDigit(const pDigit: byte);
 public
   { public declarations }
 end; </Delphi>

Next the actual code of the AddDigit procedure must be entered. Again the IDE comes to the rescue:

  • Place the blinking text cursor on the AddDigit line.
  • Press key combination Ctrl-Shift-C.

The IDE generates the definition of this new method and places the text cursor inside the empty body. We can immediately start typing.

  • Add the following code to the AddDigit procedure body:

<Delphi>edDisplay.Text := edDisplay.Text + IntToStr(pDigit)</Delphi> Note that function IntToStr() translates a numerical value, the digit, to a string value so it can be added to the display text.

Now to use this procedure for all digits 0..9:

  • Open the form (if necessary press F12 once or twice).
  • Double click on digit button 0: this will open the editor in the event handler for button 0.
  • Replace the code in the event handler with: AddDigit(0). The procedure will look like this:

<Delphi>procedure TForm1.btnDigit0Click(Sender: TObject); begin

 AddDigit(0)

end;</Delphi>

  • Do the same for digit button 1:

<Delphi>procedure TForm1.btnDigit1Click(Sender: TObject); begin

 AddDigit(1)

end;</Delphi>

Before completing this sequence for all other digit buttons, make sure that this actually does what we want.

  • Run the program (press F9).
  • Click buttons 0 and 1 a couple of times and see that it actually works.
  • End the program.

A good programmer is a lazy programmer

Now we can add event handlers to digit buttons 2..9. But then again we have the same problem of creating a lot of redundant code: AddDigit(2), AddDigit(3) etc. What if there were a way to tell the buttons apart? Luckily there is.

All components have an integer property called Tag (remember: a control is just a special kind of component that inherits this Tag property). It is a property that has no actual function. It is there for us to use as we see fit. Now what if each button would have it's digit value stored in the Tag property…

  • Open the form (if necessary press F12 once or twice).
  • Select digit button 1 (click on it once).
  • In the Object Inspector locate the Tag property and change it's value to 1.
  • Select digit button 2 (click on it once).
  • In the Object Inspector locate the Tag property and change it's value to 2.
  • Repeat this for digit buttons 3..9.

Now all digit buttons have a unique Tag value. We didn't change digit button 0 because the default Tag value already is 0. Now to make use if this Tag value:

  • Open the form.
  • Double click on digit button 0 (this will open the editor in the event handler of digit button 0).
  • Note that procedure btnDigit0Click has a parameter Sender of type TObject.

<Delphi>procedure TForm1.btnDigit0Click(Sender: TObject);</Delphi> The Sender parameter is actually a reference to the button that was pressed. Via typecasting we can use the parameter as if it was a TButton.

  • Change the code like this:

<Delphi>procedure TForm1.btnDigit0Click(Sender: TObject); begin

 AddDigit(TButton(Sender).Tag)

end;</Delphi>

It doesn't look like we have accomplished much, replacing one line of code with another. However if we were to add the code for the other digits (1..9) it would look exactly the same. So all other digits can reuse this particular method!

Let's have a closer look at the Object Inspector.

  • Open the form.
  • Select digit button 0 (btnDigit0).
  • In the Object Inspector select tab Events (see below).


tutcal oi events.png


In the object inspector we can not only change the properties of a control but also the event handlers. In the Object Inspector we can see that as soon as digit button 0 is clicked, method btnDigit0Click is called (this is the OnClick event handler).

  • On the form: select digit button 2. In the Object Inspector we can now see that there is no OnClick event handler for button 2.
  • Open the drop down list for the OnClick event and select btnDigit0Click.
  • Do this for all other digit buttons 3..9.

Now all buttons share one common procedure that does exactly what we want except for digit button 1. Remember that for digit button 1 we created an event handler btnDigit1Click that we don't really need anymore.

  • On the form: select digit button 1. In the Object Inspector we can now see that the event handler indeed is btnDigit1Click.
  • Open the drop down list for the OnClick event and select btnDigit0Click.

Now all buttons share the same event handler to add digits to the display box.

  • Run the program (press F9).
  • Click all buttons 0..9 a couple of times and see that it actually works.
  • End the program.


For the digit buttons one final thing needs to be done: event handler btnDigit1Click still exists but is not used anymore and should be deleted. The safest way to do this (for now) is to let the IDE handle it. For this to work the option Auto remove empty methods must be enabled.

  • In the menu select Environment/Options.
  • Click on Editor/Completion and Hints.
  • Enable the option 'Auto remove empty methods' (see image below).
  • Press OK.

tutcal auto remove.png

From now on all empty methods are automatically deleted as soon as the source file is saved.

  • Locate method procedure TForm1.btnDigit1Click(Sender: TObject)
  • Delete the line 'AddDigit(1)'
  • Save the file (press Ctrl-S or select from the menu File/Save). The now empty procedure is automatically deleted.

Tuning

So far so good: the calculator program compiles, runs and responds to clicks on digit buttons 0..9. But it doesn't behave exactly as we want: there's always this annoying zero at the beginning of the number and the number of allowed digits is too large.

Removing leading zeroes

Normally an integer number that's bigger (or smaller) than zero does not start with a leading zero. So our calculator should compensate for this. Luckily this is easy to implement. Remember that we have one and only one method that handles the addition of digits: AddDigit. This is the place to add logic to suppress the leading zero.

  • Locate method procedure TForm1.AddDigit(const pDigit: byte)
  • Change the code to:

<Delphi>procedure TForm1.AddDigit(const pDigit: byte); begin

 // Suppress leading zeroes when adding digits
 if edDisplay.Text = '0' then
   edDisplay.Text := IntToStr(pDigit)
 else
   edDisplay.Text := edDisplay.Text + IntToStr(pDigit)

end;</Delphi>

Limit the number of digits

This demo calculator cannot handle numbers that are too large. So we need to limit the number of digits that can be entered. Again the logical place to do this is the AddDigit method:

  • Locate method procedure TForm1.AddDigit(const pDigit: byte)
  • Change the code to:

<Delphi>procedure TForm1.AddDigit(const pDigit: byte); begin

 // Limit the number of digits
 if length(edDisplay.Text) < 8 then
 begin
   // Suppress leading zeroes when adding digits
   if edDisplay.Text = '0' then
     edDisplay.Text := IntToStr(pDigit)
   else
     edDisplay.Text := edDisplay.Text + IntToStr(pDigit)
 end;

end; </Delphi>

Operations

Now it's time to look at the actual operations we want to implement: adding, subtracting, multiplying and dividing. The way the user is going to use the calculator goes something like this:

  1. The user enters a number
  2. The user presses a function button (e.g. '+')
  3. The user enters a second number
  4. The user presses '='
  5. The program responds with the addition of the first and second number

As soon as the user presses the '=' button the program has to know three things:

  1. What was the operation?
  2. What was the first number?
  3. What was the second number?

What was the operation?

Somehow we need to register that a certain operation type was selected. And for that we need to know what operation types are available. One way to implement this is to create an enumeration type (or user defined scalar type) that contains all valid operations.

  • In the Source Editor, find the location where the form is declared.
  • Just above the form add the type declaration TOperationType for all supported operations:

<Delphi> type

 { All supported operations for our calculator }
 TOperationType = (otNone, otPlus, otMinus, otMultiply, otDivide);
 { TForm1 }
 TForm1 = class(TForm)</Delphi>
  • To temporarily store the operation, a variable is added to the private section of the form's class declaration.

<Delphi> private

   { private declarations }
   SelectedOperation: TOperationType;
   procedure AddDigit(const pDigit: byte);</Delphi>

What was the first number?

To temporarily store the first number that was entered we need a variable.

  • Add a variable to the form's private section.

<Delphi> private

   { private declarations }
   SelectedOperation: TOperationType;
   FirstNumber: longint;
   procedure AddDigit(const pDigit: byte);</Delphi>

What was the second number?

Add variable SecondNumber to the form's private section (the same as FirstNumber) and make it a longint as well.

What's on your mind