<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Constructor &#8211; Xojo Programming Blog</title>
	<atom:link href="https://blog.xojo.com/tag/constructor/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.xojo.com</link>
	<description>Blog about the Xojo programming language and IDE</description>
	<lastBuildDate>Tue, 13 Jun 2023 13:37:33 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>Creating a Number Class</title>
		<link>https://blog.xojo.com/2023/06/13/creating-a-number-class/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Tue, 13 Jun 2023 13:25:48 +0000</pubDate>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Beginner Tips]]></category>
		<category><![CDATA[Constructor]]></category>
		<category><![CDATA[Method Overload]]></category>
		<category><![CDATA[Object-Oriented]]></category>
		<category><![CDATA[Rapid Application Development]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=11585</guid>

					<description><![CDATA[In this tutorial I will show you how to create a Number class that can tell you when its value has been actually set, along with other methods to manage how it is used while demonstrating some common object-oriented techniques and features such as operator overloading. You'll be able to create a Number from an Integer, Double or String.]]></description>
										<content:encoded><![CDATA[
<p>In this tutorial I will show you how to create a Number class that can tell you when its value has been actually set, along with other methods to manage how it is used while demonstrating some common object-oriented techniques and features such as operator overloading. You&#8217;ll be able to create a Number from an Integer, Double or String.</p>



<span id="more-11585"></span>



<h3 class="wp-block-heading">The Basics of the Number Class</h3>



<p>Let&#8217;s start with the bare bones of this Number class. Add a new Class to a Xojo project and name it Number in the Inspector Panel.</p>



<p>The value of the Number class is going to be backed by a primitive double property. So add a new Property to the Number class and use the Inspector Panel with the following values:</p>



<ul class="wp-block-list">
<li><strong>Name:</strong> Value</li>



<li><strong>Type:</strong> Double</li>



<li><strong>Scope:</strong> Protected</li>
</ul>



<p>We also want to know when a value is set to any of the Number instances, so go ahead and add a new Property to the Class using the following values in the Inspector Panel:</p>



<ul class="wp-block-list">
<li><strong>Name:</strong> IsSet</li>



<li><strong>Type:</strong> Boolean</li>



<li><strong>Scope:</strong> Protected</li>
</ul>



<p>And of course we want to have the ability to enable or disable any Number instance, so its assigned value may or may not be taken into account when used in any mathematical operation, for example. Add the third of the properties required by our Number class:</p>



<ul class="wp-block-list">
<li><strong>Name:</strong> Enabled</li>



<li><strong>Type:</strong> Boolean</li>



<li><strong>Scope:</strong> Public</li>
</ul>



<p>The next step is to add some constructor Methods to our class, so we can create new instances of it covering several common cases:</p>



<ul class="wp-block-list">
<li>Creating a new instance with no value provided: IsSet property will be set to False, and the Enabled property will be set to True.</li>



<li>Creating a new instance with the Integer/Double provided: IsSet property will be set to True, and the Enabled property will be set to True.</li>



<li>Creating a new instance with the numeric value from the provided String: IsSet property will be set to True and the Enabled property will be set to True too.</li>
</ul>



<p>The default constructor for the class will be the one with no parameters. So add a new method to the Number class using the following values in the Inspector Panel:</p>



<ul class="wp-block-list">
<li><strong>Method Name:</strong> Constructor</li>



<li><strong>Scope:</strong> Public</li>
</ul>



<p>And type the following line of code in the associated Code Editor:</p>



<pre id="Xojo" class="wp-block-preformatted">Self.Enabled = True</pre>



<p>Add a second method to the class and use the following values in the Inspector Panel (this constructor will create a new instance from the received Integer/Double value):</p>



<ul class="wp-block-list">
<li><strong>Method Name:</strong> Constructor</li>



<li><strong>Parameters:</strong> value As Double</li>



<li><strong>Scope:</strong> Public</li>
</ul>



<p>And type the following lines of code in the associated Code Editor:</p>



<pre id="Xojo" class="wp-block-preformatted">Self.Constructor
Self.Value = value
Self.IsSet = True</pre>



<p>Let&#8217;s add the third constructor, the one taking a String as the parameter. Add a third method to the class using the following values in the Inspector Panel:</p>



<ul class="wp-block-list">
<li><strong>Method Name:</strong> Constructor</li>



<li><strong>Parameters:</strong> value As String</li>



<li><strong>Scope:</strong> Public</li>
</ul>



<p>And type the following lines of code in the associated Code Editor:</p>



<pre id="Xojo" class="wp-block-preformatted">Self.Constructor

Self.Value = Double.FromString(value, Locale.Raw)
Self.IsSet = True</pre>



<p>But, wait! Wouldn&#8217;t it be great if we could create new Number instances from another Number instance received as the parameter? Of course it would! So add a new Method again using the following values in the Inspector Panel:</p>



<ul class="wp-block-list">
<li><strong>Method Name:</strong> Constructor</li>



<li><strong>Parameters:</strong> value As Number</li>



<li><strong>Scope:</strong> Public</li>
</ul>



<p>And type the following lines of code in the associated Code Editor:</p>



<pre id="Xojo" class="wp-block-preformatted">Self.Constructor

If value &lt;&gt; Nil and value.IsSet And value.Enabled Then
  Self.Value = value.Value
  Self.IsSet = True
End If</pre>



<p>By now our class has four special methods, all of them with the same name: Constructor. If defined in any of your classes, this is the method that will be called/executed every time your code uses the New keyword in combination with the class data type. For example:</p>



<pre id="Xojo" class="wp-block-preformatted">Var n As New Number // This calls the by default Constructor.
Var i As New Number(10) // This calls the Constructor taking an Integer/Double as the parameter.
Var s As New Number("120.20") // This calls the Constructor taking a String as the parameter.
Var objNumber As New Number(n) // This calls the Constructor taking a Number instance as the parameter.</pre>



<p>When several methods are added to a class using the same method name but with different number of arguments or arguments data types (or returned values), that is called <strong>Method Overloading</strong> and you will find it in any object-oriented programming language. So our constructor method is overloaded to cover all the expected cases.</p>



<p>As you see, there is nothing fancy in the previous examples. I mean, creating a new instance from the received value in the constructor method is ok, but it would be even better and more simple if we could do something like:</p>



<pre id="Xojo" class="wp-block-preformatted">Var i As Number = 10
Var s As Number = "120.20"
Var objNumber = n</pre>



<h3 class="wp-block-heading">Overloading the Assignment Operator</h3>



<p>The good news is that we can do that! The Xojo programming language has the ability to overload operators too, just like we did with the constructor method! And when it is about to overload the assignment operator we implement the <a href="https://documentation.xojo.com/api/math/operator_convert.html#operator-convert">Operator_Convert</a> method. This one will be called every time our class receives a value from another data type or needs to convert itself to the expected data type; for example:</p>



<pre id="xojo" class="wp-block-preformatted">Var i As Number = 10 // 10 Integer value needs to be converted to a Number instance.
Var intValue As Integer = i // The variable "i" (Number data type) needs to be converted to an Integer data type.</pre>



<p>The most important thing to remember is that when Operator_Convert gets into play, the class Constructor is never called! So the code in the Operator_Convert method implementation needs to take care of properly initialising the instance as you expect.</p>



<p>So let&#8217;s start implementing the Operator_Convert that will be called every time a Number instance needs to be converted to an Integer or Double value.</p>



<p>Add a new method to the Number class using the following values:</p>



<ul class="wp-block-list">
<li><strong>Method Name:</strong> Operator_Convert</li>



<li><strong>Return Type:</strong> Double</li>



<li><strong>Scope:</strong> Public</li>
</ul>



<p>And type the following line of code in the associated Code Editor:</p>



<pre id="Xojo" class="wp-block-preformatted">Return If(Self.Enabled, Self.Value, 0)</pre>



<p>Add a second Operator_Convert method, this time change the returned value to a String so our Number instances internal values can be easily assigned to a String variable (or used in other operations with Strings) like this:</p>



<pre id="Xojo" class="wp-block-preformatted">Var i As Number = 10
Var s As String = i</pre>



<p>Use the following values in the associated Inspector Panel and type the line of code in the associated Code Editor:</p>



<ul class="wp-block-list">
<li><strong>Method Name:</strong> Operator_Convert</li>



<li><strong>Return Type:</strong> String</li>



<li><strong>Scope:</strong> Public</li>
</ul>



<pre id="Xojo" class="wp-block-preformatted">Return If(Self.Enabled, Self.Value.ToString(Locale.Raw), "")</pre>



<p>We need to overload the Operator_Convert method two more times so it can handle the assignment operation when the received value is at the right of the equal operator instead of the left.</p>



<p>Use the following values in the Inspector Panel for every one of the new two overloaded methods (typing the line(s) of code following each of these):</p>



<ul class="wp-block-list">
<li><strong>Method Name:</strong> Operator_Convert</li>



<li><strong>Parameters:</strong> value As Double</li>



<li><strong>Scope:</strong> Public</li>
</ul>



<pre id="Xojo" class="wp-block-preformatted">Self.Enabled = True
Self.Value = value
Self.IsSet = True</pre>



<ul class="wp-block-list">
<li><strong>Method Name:</strong> Operator_Convert</li>



<li><strong>Parameters:</strong> value As String</li>



<li><strong>Scope:</strong> Public</li>
</ul>



<pre id="Xojo" class="wp-block-preformatted">Self.Enabled = True
Self.Value = Double.FromString(value, locale.Raw)
Self.IsSet = True</pre>



<h3 class="wp-block-heading">Overloading the Add Operator</h3>



<p>Assigning values to Number variables or properties or Number instances to Integer / Double or String variables and properties is fine, but not so useful now. So the next step is adding Number instances with another Number instances, Integer / Double data types and also even with all the values from an array. To do this we need to overload the &#8220;+&#8221; (Add) operator implementing the <a href="https://documentation.xojo.com/api/math/operator_add.html#operator-add">Operator_Add</a> method in the Number class.</p>



<p>This will allow us to write code like this:</p>



<pre id="Xojo" class="wp-block-preformatted">Var n2 As Number = i + 10</pre>



<p>Here the &#8220;10&#8221; value is first converted to a Number instance that is going to be added to the &#8220;i&#8221; Number instance and then assigned to the &#8220;n2&#8221; variable.</p>



<pre id="Xojo" class="wp-block-preformatted">Var n3 As Integer = i + 10</pre>



<p>Here the &#8220;10&#8221; value is first converted to a Number instance that is added to the &#8220;i&#8221; number instance and, then, the result converted to an integer value assigned to the &#8220;n3&#8221; variable.</p>



<p>So we need to implement the Operator_Add taking a Number parameter and returning also a Number data type.</p>



<p>Add a new method to the Number class using the following values in the Inspector Panel, and typing the lines of code following them in the associated Inspector Panel:</p>



<ul class="wp-block-list">
<li><strong>Method Name:</strong> Operator_Add</li>



<li><strong>Parameters:</strong> Value As Number</li>



<li><strong>Return Type:</strong> Number</li>



<li><strong>Scope:</strong> Public</li>
</ul>



<pre id="Xojo" class="wp-block-preformatted">If value &lt;&gt; Nil Then
  Var no As New Number(If(Self.Enabled, Self.Value, 0) + value.Value)
  Return no
End If</pre>



<p>That one works well when we have a Number instance to the left of the add operation, but not when the Number instance is to the right. For that scenarios we need to overload another method: <a href="https://documentation.xojo.com/api/math/operator_addright.html">Operator_AddRight</a>.</p>



<p>Add another method to the Number class using the following values in the associated Inspector Panel:</p>



<ul class="wp-block-list">
<li><strong>Method Name:</strong> Operator_AddRight</li>



<li><strong>Parameters:</strong> value As Double</li>



<li><strong>Return Type:</strong> Double</li>



<li><strong>Scope:</strong> Public</li>
</ul>



<p>And type this line of code in the associated Code Editor:</p>



<pre id="Xojo" class="wp-block-preformatted">Return If(Self.Enabled, Self.Value, 0) + value</pre>



<h3 class="wp-block-heading">Adding Number Instances to an Array of Integers</h3>



<p>It would be also really helpful if we could add a Number to an array of integer values or even a Number instance to an array containing other array instances. For example, it would look like this in code:</p>



<pre id="Xojo" class="wp-block-preformatted">Var arrayNumbers() As Number
Var arrayIntegers() As Integer

For z As Integer = 0 To 10
  arrayNumbers.Add(System.Random.InRange(10, 200))
  arrayIntegers.Add(System.Random.InRange(10, 200))
Next

Var z1 As Number = i + arrayNumbers
Var z3 As Integer = i + arrayIntegers</pre>



<p>Of course this implies implementing new overloaded methods both for Convert_Add and Convert_AddRight. These are the implementations for overloading Convert_Add taking an Array of Doubles and also taking an Array of Number instances. I will let the Convert_AddRight implementation to you as exercice:</p>



<ul class="wp-block-list">
<li><strong>Method Name:</strong> Operator_AddRight</li>



<li><strong>Parameters:</strong> value() As Integer</li>



<li><strong>Return Type:</strong> Double</li>



<li><strong>Scope:</strong> Public</li>
</ul>



<pre id="Xojo" class="wp-block-preformatted">Var sum As Double

For Each item As Double In values
  sum = sum + item
Next

Return sum + If(Self.Enabled, Self.Value, 0)</pre>



<ul class="wp-block-list">
<li><strong>Method Name:</strong> Operator_AddRight</li>



<li><strong>Parameters:</strong> value() As Number</li>



<li><strong>Return Type:</strong> Number</li>



<li><strong>Scope:</strong> Public</li>
</ul>



<pre id="Xojo" class="wp-block-preformatted">Var sum As Double

For Each item As Number In values
  If item &lt;&gt; Nil And item.Enabled Then sum = sum + item.Value
Next

Return sum + If(Self.Enabled, Self.Value, 0)</pre>



<h3 class="wp-block-heading">Unset Number Instances</h3>



<p>The last step in this Number class is to implement the Method that will take care of Unset the instance; that is, kind of &#8220;reset&#8221; state where the value is still not defined.</p>



<p>Add a new Method to the Number class using the following values:</p>



<ul class="wp-block-list">
<li><strong>Method Name:</strong> Unset</li>



<li><strong>Scope:</strong> Public</li>
</ul>



<p>And adding the following lines of code to the associated Code Editor:</p>



<pre id="Xojo" class="wp-block-preformatted">Self.IsSet = False
Self.Value = 0</pre>



<h3 class="wp-block-heading">Conclusion</h3>



<p>As you see, method overloading is a powerful technique as we have done with the constructor method and also with the Operator_Convert, Operator_Add and Operator_AddRight methods. This Number class, with a little work, can be made to to cover other scenarios like the subtract, multiply or divide operations, among others. That wouldn&#8217;t be too difficult based on the implementations already exposed for the overloaded Operator_Add and Operator_AddRight methods. <a href="https://drive.google.com/file/d/1DfRL8WofvmdIp6dM__s_fmnswO4cx6-5/view?usp=share_link">Download</a> the Numbers class project.</p>



<p>Further Reading from the Xojo Blog Archives</p>



<p><a href="https://blog.xojo.com/2016/05/25/methods-overloading-computed-properties-setters-and-getters/">Methods Overloading: Computed Properties, Setters and Getters</a></p>



<p>More on Object-Oriented Programming from the <a href="https://blog.xojo.com/tag/object-oriented/">Xojo Blog</a> and <a href="https://documentation.xojo.com/getting_started/object-oriented_programming/index.html">Xojo Documentation</a></p>



<p><em>Javier Menendez is an engineer at Xojo and has been using Xojo since 1998. He lives in Castellón</em>, <em>Spain and hosts regular Xojo hangouts en español. Ask Javier questions on Twitter at <a href="https://twitter.com/xojoes" target="_blank" rel="noreferrer noopener">@XojoES</a> or on the <a href="https://forum.xojo.com/u/javier_menendez/summary" target="_blank" rel="noreferrer noopener">Xojo Forum</a>.</em></p>



<ul class="wp-block-social-links has-normal-icon-size is-content-justification-center is-layout-flex wp-container-core-social-links-is-layout-16018d1d wp-block-social-links-is-layout-flex"><li class="wp-social-link wp-social-link-facebook  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://www.facebook.com/goxojo" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M12 2C6.5 2 2 6.5 2 12c0 5 3.7 9.1 8.4 9.9v-7H7.9V12h2.5V9.8c0-2.5 1.5-3.9 3.8-3.9 1.1 0 2.2.2 2.2.2v2.5h-1.3c-1.2 0-1.6.8-1.6 1.6V12h2.8l-.4 2.9h-2.3v7C18.3 21.1 22 17 22 12c0-5.5-4.5-10-10-10z"></path></svg><span class="wp-block-social-link-label screen-reader-text">Facebook</span></a></li>

<li class="wp-social-link wp-social-link-x  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://x.com/xojo" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M13.982 10.622 20.54 3h-1.554l-5.693 6.618L8.745 3H3.5l6.876 10.007L3.5 21h1.554l6.012-6.989L15.868 21h5.245l-7.131-10.378Zm-2.128 2.474-.697-.997-5.543-7.93H8l4.474 6.4.697.996 5.815 8.318h-2.387l-4.745-6.787Z" /></svg><span class="wp-block-social-link-label screen-reader-text">X</span></a></li>

<li class="wp-social-link wp-social-link-linkedin  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://www.linkedin.com/company/xojo" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M19.7,3H4.3C3.582,3,3,3.582,3,4.3v15.4C3,20.418,3.582,21,4.3,21h15.4c0.718,0,1.3-0.582,1.3-1.3V4.3 C21,3.582,20.418,3,19.7,3z M8.339,18.338H5.667v-8.59h2.672V18.338z M7.004,8.574c-0.857,0-1.549-0.694-1.549-1.548 c0-0.855,0.691-1.548,1.549-1.548c0.854,0,1.547,0.694,1.547,1.548C8.551,7.881,7.858,8.574,7.004,8.574z M18.339,18.338h-2.669 v-4.177c0-0.996-0.017-2.278-1.387-2.278c-1.389,0-1.601,1.086-1.601,2.206v4.249h-2.667v-8.59h2.559v1.174h0.037 c0.356-0.675,1.227-1.387,2.526-1.387c2.703,0,3.203,1.779,3.203,4.092V18.338z"></path></svg><span class="wp-block-social-link-label screen-reader-text">LinkedIn</span></a></li>

<li class="wp-social-link wp-social-link-github  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://github.com/topics/xojo" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M12,2C6.477,2,2,6.477,2,12c0,4.419,2.865,8.166,6.839,9.489c0.5,0.09,0.682-0.218,0.682-0.484 c0-0.236-0.009-0.866-0.014-1.699c-2.782,0.602-3.369-1.34-3.369-1.34c-0.455-1.157-1.11-1.465-1.11-1.465 c-0.909-0.62,0.069-0.608,0.069-0.608c1.004,0.071,1.532,1.03,1.532,1.03c0.891,1.529,2.341,1.089,2.91,0.833 c0.091-0.647,0.349-1.086,0.635-1.337c-2.22-0.251-4.555-1.111-4.555-4.943c0-1.091,0.39-1.984,1.03-2.682 C6.546,8.54,6.202,7.524,6.746,6.148c0,0,0.84-0.269,2.75,1.025C10.295,6.95,11.15,6.84,12,6.836 c0.85,0.004,1.705,0.114,2.504,0.336c1.909-1.294,2.748-1.025,2.748-1.025c0.546,1.376,0.202,2.394,0.1,2.646 c0.64,0.699,1.026,1.591,1.026,2.682c0,3.841-2.337,4.687-4.565,4.935c0.359,0.307,0.679,0.917,0.679,1.852 c0,1.335-0.012,2.415-0.012,2.741c0,0.269,0.18,0.579,0.688,0.481C19.138,20.161,22,16.416,22,12C22,6.477,17.523,2,12,2z"></path></svg><span class="wp-block-social-link-label screen-reader-text">GitHub</span></a></li>

<li class="wp-social-link wp-social-link-youtube  wp-block-social-link"><a rel="noopener nofollow" target="_blank" href="https://www.youtube.com/c/XojoInc" class="wp-block-social-link-anchor"><svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M21.8,8.001c0,0-0.195-1.378-0.795-1.985c-0.76-0.797-1.613-0.801-2.004-0.847c-2.799-0.202-6.997-0.202-6.997-0.202 h-0.009c0,0-4.198,0-6.997,0.202C4.608,5.216,3.756,5.22,2.995,6.016C2.395,6.623,2.2,8.001,2.2,8.001S2,9.62,2,11.238v1.517 c0,1.618,0.2,3.237,0.2,3.237s0.195,1.378,0.795,1.985c0.761,0.797,1.76,0.771,2.205,0.855c1.6,0.153,6.8,0.201,6.8,0.201 s4.203-0.006,7.001-0.209c0.391-0.047,1.243-0.051,2.004-0.847c0.6-0.607,0.795-1.985,0.795-1.985s0.2-1.618,0.2-3.237v-1.517 C22,9.62,21.8,8.001,21.8,8.001z M9.935,14.594l-0.001-5.62l5.404,2.82L9.935,14.594z"></path></svg><span class="wp-block-social-link-label screen-reader-text">YouTube</span></a></li></ul>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Create a Preferences Class with Operator_Lookup</title>
		<link>https://blog.xojo.com/2018/06/20/create-a-preferences-class-with-operator_lookup/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Wed, 20 Jun 2018 10:00:58 +0000</pubDate>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Constructor]]></category>
		<category><![CDATA[Method Overload]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[Singleton]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=4381</guid>

					<description><![CDATA[Create a Preferences Class with Operator_Lookup: We have at our disposal an operator we can overload: Lookup. Let's explore those advantages and features while building a Preferences class we can use in any of our projects.]]></description>
										<content:encoded><![CDATA[<p>Xojo is an <a href="https://en.wikipedia.org/wiki/Object-oriented_programming">Object Oriented Programming Language</a> and, among other things, that means that it supports <a href="https://blog.xojo.com/2016/05/25/methods-overloading-computed-properties-setters-and-getters/">Methods Overloading</a>. We have seen in other posts that some of these overloaded methods can be Class Constructors, but, there are others things you can do. For example, we can overload the operators. These are the methods in charge of adding two instances of the same class, subtracting, multiplying or dividing them. But we also have at our disposal another operator we can overload: <b>Lookup</b>. What advantages does this give us and how it does it work? Let&#8217;s explore it while building a Preferences class we can use in any of our projects.<span id="more-4381"></span></p>
<p>When we define and implement the <b>Operator_Lookup</b> method in our classes, we will be able to use the dot notation to access and assign a value to a class member that has not been defined for the class! That is, it will be the code implemented in this method that will decide how it will act, not the Xojo Compiler. Among other possibilities, this will bring us the flexibility to create a Preferences class that is not attached to a particular project, and that is multiplatform, of course, backed by as many pairs of Keys/Values in a Dictionary as we need to store our apps preferences. This way we can use the simple dot notation both to store and assign the stored values. Let&#8217;s put this into practice.</p>
<p>The first step is adding a new Class item to the project without assigning a Super class; that is, this will be a base class. For this example, we will use <code>MyPreferences</code> as the name of the class. Then, we will add a property with <code>Data</code> as the Name and <code>Xojo.Core.Dictionary</code> as the data type, setting its scope to Private (this means that the property will be accessible only from the own class). This property will act as the storage for the Key/Value pairs used for our Preference Class.</p>
<p>Add now a new <b>Constructor</b> method in charge of initializing the just defined Dictionary property:</p>
<ul>
<li><b>Name</b>: Constructor</li>
<li><b>Scope</b>: Public</li>
</ul>
<p>And put this line of code in the Code Editor for the Constructor method:</p>
<pre>Data = New Xojo.Core.Dictionary</pre>
<p>Now we will add the method that we are really interested in. This is, the overload for the Operator_Lookup method:</p>
<ul>
<li><b>Name</b>: Operator_Lookup</li>
<li><b>Parameters</b>: key as string, assigns value as auto</li>
<li><b>Scope</b>: Public</li>
</ul>
<p>Writing the following line of code in the resulting Code Editor:</p>
<pre>data.Value( key ) = value</pre>
<p>Once implemented, we can take advantage of the feature. If we add the Open Event to the project and write the below snippet of code, we will see how we can use the dot notation to use and access class members that have never been added to the class. These members are <em>captured</em> by the <code>Operator_Lookup</code> method, adding the member as the key for a new entry in the dictionary (this is the text we write after the dot) and assigning to it the value we put after the equal symbol (the assignation operator); thanks to the use of the <code>assigns</code> keyword in the parameters declaration for the <code>Operator_Lookup</code> method.</p>
<pre>Dim pr As New MyPreferences
pr.page = 10
pr.index = "20"
pr.baseColor = &amp;c204060</pre>
<p>As you can see, <code>Page</code>, <code>Index</code> and <code>BaseColor</code> are not members of our class; these are captured as Keys for the Dictionary thanks to the Operator_Lookup operator. In addition, you can see how we can assign several types of values to these: an Integer, a String and a Color value.</p>
<h2>Retrieving data with Operator_Lookup</h2>
<p>Now, how can we retrieve values for these not existing members using the dot notation? As you probably guessed, we need to add an additional method that overloads Operator_Lookup. In this case the method signature will accept as the parameter the Key we want to retrieve (the class member put after the dot), returning always a String, in order to simplify this example. Thus, add a new method for the class using the following signature:</p>
<ul>
<li><b>Name</b>: Operator_Lookup</li>
<li><b>Parameters</b>: Key As String</li>
<li><b>Return Type</b>: String</li>
<li><b>Scope</b>: Public</li>
</ul>
<p>Writing the following code in the associated Code Editor:</p>
<pre>Dim a As Auto
Dim s As String
If data.HasKey(key) Then
  a = data.Value(key)
  Dim info As Xojo.Introspection.TypeInfo
  info = xojo.Introspection.GetType(a)
  If info = GetTypeInfo(Text) Or info = GetTypeInfo(String) Then
    s = a
  Elseif info = GetTypeInfo(Integer) Then
    s = CType(a, Integer).totext
  Elseif info= GetTypeInfo(Color) Then
    Dim c As Color = a
    s = Str(c)
  End If
End If
Return s</pre>
<p>As you can see, and after verifying that the Dictionary has the Key, we use the <b>Introspection</b> mechanisms provided by the language in order to see what type is associated with the key. Once we have its type, we will convert the value to a String using the appropriate approach for each case: an Integer, a Text/String or a Color. Of course, for brevity, this example doesn&#8217;t take into account other possible value types; but that is something you can implement yourself!</p>
<p>Let&#8217;s go back to the Open Event for the project and add the following line of code at the end:</p>
<p><code>MsgBox pr.page + EndOfLine + pr.index  + EndOfLine + pr.baseColor</code></p>
<p>Run it and observe how we can assign values and retrieve them (always as a String) simply using the dot notation. We can take this class from one project to other and use the dot notation to reference the elements we want to save and retrieve as preferences.</p>
<p><iframe title="Obtén la máxima flexibilidad con Operator_Lookup" width="500" height="375" src="https://www.youtube.com/embed/Tya8tbi9xIM?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe></p>
<h2>Final Word</h2>
<p>If you decide to use this approach for your projects, there are some considerations you have to take into account. For example, you will not be able to take advantage of the Autocompletion feature provided by the IDE. In addition, we will have to pay special attention to write exactly the same &#8220;member&#8221; in all the cases we want refer to it; otherwise we will be using a different key with unexpected results. After all, once implemented, Operator_Lookup for the class the Compiler will not complain about the undefined members you are trying to access!</p>
<p>It would also be very easy to expand the class so it can work with other data types; adding an additional method to serialize the Key/Values pairs so they can be stored on file/database for a later retrieval and reconstruction via an additional Constructor. Finally, it is very probable that you only want to use a MyPreferences instance in your app, so you could implement this class as a <a href="https://blog.xojo.com/2016/06/08/design-patterns-in-xojo-singleton/">Singleton</a>. Do you dare? If you do, <a href="https://twitter.com/AprendeXojo">tell me about it</a>!</p>
<p><em>Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has be using Xojo since 1998. He manages <a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers, Markdown Parser for Xojo, HTMLColorizer for Xojo and the Snippery app, among others</em></p>
<p>*<a href="https://www.aprendexojo.com/2018/06/comprobar-y-anadir-valores-en-tiempo-de-ejecucion/">Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Control Subclass Constructors</title>
		<link>https://blog.xojo.com/2018/01/11/control-subclass-constructors/</link>
		
		<dc:creator><![CDATA[Norman Palardy]]></dc:creator>
		<pubDate>Thu, 11 Jan 2018 07:12:12 +0000</pubDate>
				<category><![CDATA[Learning]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Constructor]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=3641</guid>

					<description><![CDATA[A constructor is a special method that is used to initialize a class. They are very handy, but when you use them with control subclasses you have to be aware of how a control's properties are initialized. Perhaps you've run into this situation:

“I have a constructor on my control and the values that I set in the constructor don’t stick.”]]></description>
										<content:encoded><![CDATA[<p>A constructor is a special method that is used to initialize a class. They are very handy, but when you use them with control subclasses you have to be aware of how a control&#8217;s properties are initialized. Perhaps you&#8217;ve run into this situation:</p>
<p>“I have a constructor on my control and the values that I set in the constructor don’t stick.”<span id="more-3641"></span></p>
<p>But, indeed IF you put a break point in the constructor for your control subclass you will see it definitely gets called. And the values you set are present when the constructor is exited.</p>
<p>What most people miss is that if you made your public properties into computed ones and put a break point in the setter you’d find that this gets called AFTER the constructor.</p>
<p>And this is REALLY relevant.</p>
<p>Normally a control instance on a layout is created and configured using code much like:</p>
<pre>  // the next line obviously calls the constructor
  dim c as Control = new &lt;your custom control subclass name&gt;

  // and IF you had a computed property and
  // set a break point in each computed property setter
  // you will see each setter get called in turn

  c.SetAllProperties( paramarray of property names and values )</pre>
<p>and so the first calls to the setters are what put the values you set in the Inspector onto your control.</p>
<p>And this is what people do not usually expect.</p>
<p>But how else would you get all those properties onto the control and NOT require every control subclass to have a special constructor ?</p>
<p>Usually the advice is “put your set up code in the Open event” which is often too late.</p>
<p>IF you do set property values you want to keep in the constructor there are a few choices.</p>
<ol>
<li>Don&#8217;t make these properties “public” as every public property will be set in the “SetAllProperties” call. PER INSTANCE properties should be unique to that instance and so they all get set if they are public. Private and protected properties won’t.</li>
<li>Make your public properties into computed properties and “skip” the first call to the setter so whatever value you set in the constructor does not get written over by the call to SetAllProperties.</li>
<li>Make the properties public and set the initial values in the inspector (which is IMHO the &#8220;right&#8221; way to do this)</li>
</ol>
<p>I’ve put together <a href="http://great-white-software.com/miscellaneous/control_constructors.xojo_binary_project.zip">a sample</a> you can put break points in to see that the constructor and setters for public properties are called exactly as described.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>TextField with Autocomplete</title>
		<link>https://blog.xojo.com/2016/08/10/textfield-with-autocomplete/</link>
					<comments>https://blog.xojo.com/2016/08/10/textfield-with-autocomplete/#comments</comments>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Wed, 10 Aug 2016 08:00:51 +0000</pubDate>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Constructor]]></category>
		<guid isPermaLink="false">http://blog.xojo.com/?p=1540</guid>

					<description><![CDATA[Wouldn&#8217;t it be nice to have&#160;a TextField with Autocomplete for&#160;Xojo Apps, like&#160;we are used to in the Xojo IDE? You know, you start to type&#8230;]]></description>
										<content:encoded><![CDATA[<p>Wouldn&#8217;t it be nice to have&nbsp;a <strong>TextField</strong> with Autocomplete for&nbsp;<strong>Xojo</strong> Apps, like&nbsp;we are used to in the Xojo IDE? You know, you start to type a word and the autocomplete feature suggests a possible matching word and finally you just have to press the &#8216;Tab&#8217; key in order to complete the writing of the word. Let&#8217;s see how we can implement it, using&nbsp;language features like Subclassing and Class Interface, among others!</p>
<h2>Creating the Class Interface</h2>
<p>Our Xojo project will use&nbsp;three main items: a subclass from the TextField class, a Class Interface definition, and a Class that will do the job of&nbsp;the Dictionary containing the suggested words for the Autocomplete feature and that will conform to the Class Interface. This way, you&#8217;ll be able to use any object as the Dictionary source, as long as&nbsp;it conforms to the expected Class Interface.</p>
<p><strong>Note</strong>: The Dictionary referred to here is not the Xojo Dictionary class, but is our collection of suggested words for use by autocomplete.</p>
<p>In fact let&#8217;s start creating a Class Interface; so run the Xojo IDE and create a new Desktop project.</p>
<p><img fetchpriority="high" decoding="async" class="wp-image-7071 size-full aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/08/AddClassInterface.png" alt="" width="322" height="289" srcset="https://blog.xojo.com/wp-content/uploads/2016/08/AddClassInterface.png 322w, https://blog.xojo.com/wp-content/uploads/2016/08/AddClassInterface-300x269.png 300w" sizes="(max-width: 322px) 100vw, 322px" /></p>
<ol>
<li>Add a new <a href="http://developer.xojo.com/userguide/interfaces">Class Interface</a> to the project selecting <strong>Insert &gt; Class Interface</strong>.</li>
<li>Write &#8216;TextAutocompleteSource&#8221; in the Name field of the Inspector. This one will be the Data Type for the created Class Interface.</li>
<li>Select the icon for the&nbsp;&#8216;TextAutocompleteSource&#8217; in the Navigator&nbsp;(the leftmost column in the IDE Window), open the contextual menu and choose the &#8216;Add to &#8220;TextAutocompleteSource&#8221; &gt; Method&#8217; option. This action will bring us to the Inspector, so we can define the new Method signature.</li>
<li>The first of the methods will be in charge of adding a new word to the dictionary, so use &#8216;AddWordToDictionary&#8217; as the Method Name, and type &#8216;Value As String&#8217; in the Parameters field.</li>
<li>Add a second Method, name it &#8216;Match&#8217;, type &#8216;Value As String&#8217; in the Parameters field, and &#8216;String&#8217; for the &#8216;Return Type&#8217; field. This will be the invoked method in order to find and return a word suggested for the received string.</li>
</ol>
<p>That&#8217;s all we need for our Class Interface. Simple, isn&#8217;t? Remember that Class Interfaces just deal with Method definitions, and the classes that conform to it will be responsible for&nbsp;implementing the code for the&nbsp;methods.</p>
<h2>Defining our Dictionary</h2>
<p>Now is time to create a new class that will play the role of the main Dictionary for the app of this Tutorial. This one will implement, in fact, the Class Interface defined in the previous section. This means that will implement the real functionality for the methods defined in the TextAutocompleteSource Class Interface.</p>
<ul>
<li>Create a new <a href="http://developer.xojo.com/userguide/classes">Class</a> selecting Insert &gt; Class from the main Toolbar or from the Insert menu.</li>
<li>Type &#8216;StringStack&#8217; in the Inspector as the name of the new Class. This will be the name for the just created Data Type.</li>
<li>From the Inspector, click on the Choose button near to the &#8216;Interfaces&#8217; label. As a result, this action will open a new Window showing all the available Class Interfaces…&nbsp;including the one created by us in the previous section! Select this one (TextAutocompleteSource) and confirm the selection clicking the &#8216;OK&#8217; button.</li>
</ul>
<p><img decoding="async" class="aligncenter wp-image-7072 size-medium" src="https://blog.xojo.com/wp-content/uploads/2016/08/AddInterface-300x282.png" alt="" width="300" height="282" srcset="https://blog.xojo.com/wp-content/uploads/2016/08/AddInterface-300x282.png 300w, https://blog.xojo.com/wp-content/uploads/2016/08/AddInterface-768x723.png 768w, https://blog.xojo.com/wp-content/uploads/2016/08/AddInterface.png 1024w" sizes="(max-width: 300px) 100vw, 300px" /></p>
<ul>
<li>As result, Xojo will add the methods declared in the selected Class Interface. We will implement the code for these two methods in a later step.</li>
</ul>
<p><img loading="lazy" decoding="async" class="wp-image-7074 size-full aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/08/InterfaceMethods.png" alt="" width="410" height="156" srcset="https://blog.xojo.com/wp-content/uploads/2016/08/InterfaceMethods.png 410w, https://blog.xojo.com/wp-content/uploads/2016/08/InterfaceMethods-300x114.png 300w" sizes="auto, (max-width: 410px) 100vw, 410px" /></p>
<ul>
<li>Add a new Property to the class: with StringBack selected, choose Insert &gt; Property. In the resulting Inspector, type &#8216;Collector(-1)&#8217; in the Name field. This means, that our Property will be an Empty Array. Type &#8216;String&#8217; for the &#8216;Type&#8217; field and choose &#8216;Private&#8217; as the Scope for the property.</li>
<li>Let&#8217;s implement the code for the Class Interface methods! Select the &#8216;addWordToDictionary&#8217; method and type the following code in the associated Code Editor:</li>
</ul>
<pre>if not Value.IsEmpty then Collector.Addrow(Value)</pre>
<p>Select now the &#8216;Match&#8217; method and type the following code in the associated Code Editor:</p>
<pre>Var n As Integer = Value.Length
Var t As String
For Each item As String In Collector
  t = element.Middle(0, n)
  if t = Value then return item
Next
Return ""</pre>
<p>This method is the one responsible to find a suggested word for the received string. Probably you&#8217;ll want to improve the algorithm in your own implementation (depending mainly on the kind of object you will use as a Dictionary), but this one will serve for our testing app.</p>
<h2>Adding a Constructor to the Class</h2>
<p>Now we are going to define a very special method to the Class: the <a href="http://developer.xojo.com/userguide/constructors-and-destructors$Constructors">Constructor</a>. When a Class has this method it will execute the code from this method every time we create a new instance (object) from the Class. Usually we use the class Constructor (you can have several of them thanks to the OOP feature of <a href="http://developer.xojo.com/userguide/oop-design-concepts$Overloading">Method Overloading</a>) to define the initial state of the new instantiated object. In our case, we will use the Constructor to assign the initial state of the dictionary (the Collector property we&#8217;ve defined in a previous step) during the instantiation of the object.</p>
<p><img loading="lazy" decoding="async" class="wp-image-7075 size-full aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/08/Constructor.png" alt="" width="400" height="207" srcset="https://blog.xojo.com/wp-content/uploads/2016/08/Constructor.png 400w, https://blog.xojo.com/wp-content/uploads/2016/08/Constructor-300x155.png 300w" sizes="auto, (max-width: 400px) 100vw, 400px" /></p>
<ol>
<li>Add a new method to the Class (Insert &gt; Method). Next, select the &#8216;Constructor&#8217; item from the &#8216;Method Name&#8217; drop-down menu or type it.</li>
<li>As we would do with a regular Method, we can modify the Constructor method signature to define, for example, the amount and type of the parameters. In fact, for our Constructor we will type &#8216;Value() As String&#8217; for the Parameters field.</li>
</ol>
<p>Add the following code to it:</p>
<pre>Collector = Value</pre>
<h2>Subclassing: TextField Specialization</h2>
<p>We have finished the auxiliary items needed for the project, so it is time to focus on the main point: create a TextField subclass to include the autocomplete feature on it.</p>
<ol>
<li>Add a new class to the project using Insert &gt; Class. Type &#8216;TextFieldAutocomplete&#8217; as the Class name in the Inspector, and type &#8216;TextField&#8217; as its &#8216;Super&#8217; class.</li>
<li>Add a new property (Insert &gt; Property). Type &#8216;Autocomplete&#8217; as the property Name, &#8216;Boolean&#8217; as the Type, and &#8216;True&#8217; for the Default field. Finally, select the &#8216;Public&#8217; option for the scope. This property will let us to use the objects from the class as regular TextField, without autocompletion, or with the Autocomplete functionality.</li>
<li>Add another property, typing &#8216;AutocompleteSource&#8217; for the property Name, setting the scope to &#8216;Public&#8217; and its type to &#8216;TextAutocompleteSource&#8217;. That is the Data Type we have created as a Class Interface. This allows us to use any object that conforms to TextAutocompleteSource as the source for the Autocompletion Dictionary.</li>
<li>Let&#8217;s add a third property. In this case, use &#8216;TabKeyAutcompletes&#8217; as the property name, &#8216;Boolean&#8217; for the Type, set the Scope to Public, and its default value to &#8216;True&#8217;. We will use this property to set the behaviour of the Tab key between autocomplete the suggested word, or change to its regular behaviour when used on a TextField control.</li>
</ol>
<h2>Shared Properties</h2>
<p>All the properties created for the subclass are <a href="http://developer.xojo.com/userguide/properties-methods-and-events$InstanceProperties">Instance Properties</a>. That is, every new instance (object) from this class will have its own set of values for these properties. In some cases, however, we want to share the value of one or several properties for all the class instances…and this is what we can achieve using the <a href="http://developer.xojo.com/userguide/properties-methods-and-events$Shared%20Properties">Shared Properties</a>.</p>
<p>We will use two of these shared properties for our TextFieldAutocomplete class to see them in action. One of these will let us use the Suggestions Dictionary globally for all the class instances, always the property is not set to Nil. The second one will be an Array of Strings that will contain all the characters that we want to exclude from the typed on the textfield.</p>
<ol>
<li>Add a new Shared Property to the Class, typing &#8216;globalAutocompleteSource&#8217; for the Name field, setting the Scope to &#8216;Public&#8217; and typing &#8216;TextAutocompleteSource&#8217; as the Data Type for the Property.</li>
<li>Add the second Shared Property typing &#8216;SpecialCharacters(-1)&#8217; as its name, setting the Scope to &#8216;Protected&#8217; and &#8216;String&#8217; for the Data Type.</li>
</ol>
<h2>TextFieldAutocomplete: a Matter of Methods</h2>
<p>The next step is to add a couple of method to our class: the public interface. With them, the user of the class can set the no allowed characters.</p>
<ul>
<li>Add a new method to the class typing &#8216;AddSpecialCharacters&#8217; as the name, &#8216;Value() as String&#8217; for the Parameters field, and setting the Scope to &#8216;Public&#8217;. Type this line of code in the associated Code Editor for the method:</li>
</ul>
<pre>SpecialCharacters = Value</pre>
<ul>
<li>Add the second method, using &#8216;SpecialCharacter&#8217; as the method name, &#8216;Value as String&#8217; for the parameters field, &#8216;Boolean&#8217; as returned Type and setting the Scope to &#8216;Protected&#8217;. Type this block of code for the method:</li>
</ul>
<pre>If SpecialCharacters.LastRowIndex &gt; 0 Then
  For Each item As String In SpecialCharacters
    If item = Value then Return true
  Next
End If
Return False</pre>
<h2>Handling Events</h2>
<p>Our TextFieldAutocomplete class needs to be aware of every key down, so we are going to add the handler triggered in response of this event.</p>
<ul>
<li>Make sure that the &#8216;TextFieldAutocomplete&#8217; item is selected on the Navigator&nbsp;and select Insert &gt; Event Handler. This action will show&nbsp;a new window with&nbsp;all the available Events for the class. Select the KeyDown event and confirm clicking on the &#8216;OK&#8217; button.</li>
</ul>
<p><img loading="lazy" decoding="async" class="wp-image-7076 size-full aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/08/KeyDownEvent.png" alt="" width="605" height="326" srcset="https://blog.xojo.com/wp-content/uploads/2016/08/KeyDownEvent.png 605w, https://blog.xojo.com/wp-content/uploads/2016/08/KeyDownEvent-300x162.png 300w" sizes="auto, (max-width: 605px) 100vw, 605px" /></p>
<ul>
<li>Select the just added KeyDown event and type the following block of code. This is the place where we put the main logic for the class!</li>
</ul>
<pre>If Autocomplete = False Then Return RaiseEvent KeyDown(Key)

If SpecialCharacter(key) = True Then Return False

If Asc(key) = 9 And TabKeyAutocompletes = True And Me.SelectionLength &gt; 0 Then
  Me.SelectionStart = Me.value.Length
  Me.SelectionLength = 0
  Return True
End If

Var tempText As String = Me.Value.Left(Me.SelectionStart) + key

Var matchingText As String

If AutocompleteSource &lt;&gt; Nil Then

  matchingText = AutocompleteSource.Match(tempText)

Elseif GlobalAutocompleteSource &lt;&gt; Nil Then

  matchingText = GlobalAutocompleteSource.Match(tempText)
End If

If matchingText &lt;&gt; "" Then
  Me.Value = matchingText
  Var startOffset As Integer = tempText.Length
  Me.SelectionStart = startOffset
  Me.SelectionLength = matchingText.Length-startOffset
  Return True
End If

Return false</pre>
<h2>Adding Class Events</h2>
<p>Our class uses&nbsp;the KeyDown event, and that means that it will not be available for the new controls added to the project that would be based on this class. The solution? The Xojo language allows us to <a href="http://developer.xojo.com/userguide/properties-methods-and-events$Events">define new events</a> for&nbsp;our classes, and we will use that feature in order to &#8220;duplicate&#8221; the signature of the used event on the class.</p>
<p>Make sure it is selected the &#8216;TextFieldAutocomplete&#8217; item in the Navigator&nbsp;and then select Insert &gt; Event Definition. The last action will bring us to the Inspector. Type &#8216;KeyDown&#8217; as the Event Name, &#8216;Key as String&#8217; as the Parameter, and &#8216;Boolean&#8217; as Returned Type.</p>
<p>As you can see in the block of code of the previous section, we will call our defined event using the statement &#8216;RaiseEvent&#8217;, passing as parameter the same &#8216;Key&#8217; String received in the original event.</p>
<h2>Design the User Interface</h2>
<p>Everything is now ready to test our Autocomplete TextField with Xojo! The first step is to choose the Window1 item in the Navigator, using the available UI Controls in the Library in order to design the interface as shown in this screenshot:</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-7077 size-large" src="https://blog.xojo.com/wp-content/uploads/2016/08/CompleteInterface-1024x379.png" alt="" width="1024" height="379" srcset="https://blog.xojo.com/wp-content/uploads/2016/08/CompleteInterface-1024x379.png 1024w, https://blog.xojo.com/wp-content/uploads/2016/08/CompleteInterface-300x111.png 300w, https://blog.xojo.com/wp-content/uploads/2016/08/CompleteInterface-768x284.png 768w, https://blog.xojo.com/wp-content/uploads/2016/08/CompleteInterface.png 1304w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></p>
<p>In fact, you have to use two CheckBox controls, one PushButton and one TextFieldAutocomplete, dragging the last one from the Navigator&nbsp;over the Window1 Layout Editor.</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-7078 size-full" src="https://blog.xojo.com/wp-content/uploads/2016/08/TextFieldSuperClass.png" alt="" width="1006" height="379" srcset="https://blog.xojo.com/wp-content/uploads/2016/08/TextFieldSuperClass.png 1006w, https://blog.xojo.com/wp-content/uploads/2016/08/TextFieldSuperClass-300x113.png 300w, https://blog.xojo.com/wp-content/uploads/2016/08/TextFieldSuperClass-768x289.png 768w" sizes="auto, (max-width: 1006px) 100vw, 1006px" /></p>
<p>Double click the &#8216;CheckBox1&#8217; labeled as &#8216;Autocomplete&#8217; and add a new Event Handler. Choose &#8216;Action&#8217; and click on &#8216;Ok&#8217; to confirm the selection. Type the following line of code in the resulting Code Editor for the added &#8216;Action&#8217; Event Handler:</p>
<pre>TextField1.Autocomplete = me.Value</pre>
<p>Repeat the same operation on the &#8220;CheckBox2&#8221;. In this case, type the following line of code on the &#8216;Action&#8217; Event Handler:</p>
<pre>TextField1.TabKeyAutocompletes = me.Value</pre>
<p>Lastly, add the &#8216;Action&#8217; Event Handler on the &#8216;PushButton1&#8217; control, typing the following line of code:</p>
<pre>Stack.AddWordToDictionary TextField1.Text</pre>
<h2>Start Your&nbsp;Engines!</h2>
<p>Now we need to&nbsp;define the &#8216;Stack&#8217;&nbsp;and the code responsible of putting our demo to work.</p>
<p>Make sure that the &#8216;Window1&#8217; item is selected in the Navigator&nbsp;and add a new Property using &#8216;Stack&#8217; as its name, set the Scope to &#8216;Public&#8217; and the Type to &#8216;StringStack&#8217;. That is the base class previously defined and that conforms to the TextAutocompleteSource protocol.</p>
<p>Now, add the &#8216;Open&#8217; Event Handler to &#8216;Window1&#8217; and type the following block of code:</p>
<pre>Stack = New StringStack(Array("object", "objection", "objective", "objector", _
  "desert", "deserve", "descend", "destroyer", "destruction", _
  "trail", "train", "trainer", "cup", "cure", "curiosity"))

TextField1.AddSpecialCharacters(array(chr(8)))
TextField1.AutocompleteSource = Stack</pre>
<p>As you can see, when we instantiate a new object from the StringStack class, we use the Constructor to pass the Array of Strings. This way we have a simple dictionary whose contents allow us to test the Autocomplete TextField. Obviously, we can change the Dictionary used to any other object that conforms to the &#8216;TextAutocompleteSource&#8217; protocol… even if it is a database!</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-7079 size-full" src="https://blog.xojo.com/wp-content/uploads/2016/08/ProjectRunning.png" alt="" width="690" height="288" srcset="https://blog.xojo.com/wp-content/uploads/2016/08/ProjectRunning.png 690w, https://blog.xojo.com/wp-content/uploads/2016/08/ProjectRunning-300x125.png 300w" sizes="auto, (max-width: 690px) 100vw, 690px" /></p>
<p>Run the project and start to type on the Autocomplete TextField. If you start typing the characters&nbsp;of any of the words in the &#8220;Dictionary&#8221;, you&#8217;ll see the TextField will show a suggestion for Autocompletion. Press the &#8216;Tab&#8217; key… and done!</p>
<p>You can download the Example Project used in this tutorial from <a href="https://www.dropbox.com/s/0yovqk1uvb8tqx1/TextField-Autocomplete.zip?dl=1">this link</a>.</p>
<p>You can <a href="https://youtu.be/VIrKvjZfNGs" target="_blank" rel="noopener noreferrer">watch the video</a> (in Spanish only) that&nbsp;talks you though this example.</p>
<p><a href="http://www.aprendexojo.com/2015/09/subclases-e-interfaces-de-clase-en-xojo/" target="_blank" rel="noopener noreferrer">*Read this post in Spanish</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.xojo.com/2016/08/10/textfield-with-autocomplete/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
	</channel>
</rss>
