Currency Converter

In this tutorial we will create a simple currency converter application. Given some initial dollar amount and the exchange rate, we will write Smalltalk code to compute the amount in another currency.

Download CurrencyConverter.st

The user will have to enter the amount to convert in the top text field and press the Convert button. The resulting amount will display in the bottom field.

  1. Open a workspace.

    Select Workspace from the Tools menu. A workspace window appears.

  2. Initialize the exchange rate variable.
    exchangeRate := 1.33.
  3. Initialize the window.

    The window has title, position, and some extent.

    (window := MacWindowFrame new)
      text: 'Currency Converter';
      position: 20@60;
      extent: 300@160.
  4. Initialize the amount field label.

    The label has text and some extent.

    (amountLabel := MacTextLabel new)
      text: 'Amount to convert:';
      extent: 100@15.
  5. Initialize the amount field.

    The field has some extent.

    (amountField := MacTextField new)
      extent: 100@15.
  6. Initialize the result label and field.

    Apply the same settings as for the amount label and field. Additionally, the result field must be disabled because it should not accept user input.

    (resultLabel := MacTextLabel new)
      text: 'Result:';
      extent: 100@15.
    
    (resultField := MacTextField new)
      disable;
      extent: 100@15.
  7. Initialize the Convert button.

    The Convert push button is the default button in the window. When this button is clicked, the value in the amount field is multiplied by the exchange rate and the result shown in the result field.

    (convertButton := MacPushButton new)
      text: 'Convert';
      beDefault;
      extent: 100@20;
      when: #clicked evaluate: [
        resultField text: (
          amountField text asNumber * exchangeRate
        ) asString].
  8. Setup the window.

    Add the labels, fields, and button controls to the window and lay them out vertically.

    window
      layout: LinearLayout new beVertical;
      addControl: amountLabel;
      addControl: amountField;
      addControl: resultLabel;
      addControl: resultField;
      addControl: convertButton layoutConstraints: (
        LinearLayoutConstraints new
          anchorRight;
          stretchHorizontally: false;
          yourself).
  9. Open the window.

    The window has to be opened for the user to interact with it.

    window open
  10. Run the script.

    Select the contents of the workspace and evaluate it.