Basic Object/Class overview: Digital Clock example.

Create a digital time clock and understand objects

Page 1 of 1

4 Replies - 3016 Views - Last Post: 13 April 2009 - 06:56 AM Rate Topic: -----

#1 kryton46   User is offline

  • New D.I.C Head
  • member icon

Reputation: 6
  • View blog
  • Posts: 44
  • Joined: 29-December 08

Basic Object/Class overview: Digital Clock example.

Posted 03 January 2009 - 09:13 PM

I just wanted to share with fellow beginners, how to use a timer to show correctly formatted time like HH:MM:SS:tenths on a label or text box placed on a form and implementing a simple class and object.

Let me explain classes in general. When i first started learning OO design, objects baffled me as i was used to procedural VB6.0 syntax! However, the simplicity of objects began to slowly sink in (and reading many eBooks) and they are powerful for one main reason - objects encapsulate code, i.e. think of objects as a shoe box; all your code is contained in a shoe box and you don't need to care what the code is, all you care about is what methods and properties are available. Don't worry about things like inheritance, delegates, reflection, polymorphism, etc, they are all scare words you don't need to know about when first understanding OO, just understand that classes are black boxes of code and the battle is half won.

Using intellisense shows you this easily (much better in VB than C# imho, but i'm a noob, so i may stand corrected). For example, dropping a text box on a form, if you type textbox1. then intellisense shows you all the methods and properties (class variables) available. You don't care how the code is written, just that it is there as a simple function call like textbox1.text or textbox1.width, etc.

I also thought along these lines when i first began to learn OO a few months ago. Imagine you create a simple form with buttons, labels, text boxes, etc and then view the form1.vb code. This is called client code and think of it as the right page of a book. Now if you create an object, this would be the left page, so the left and right pages are two distinct entities separated by the spine of the book. The only way the two pages can 'talk' to one another is by creating an instance of the class in the client code (right page) by doing dim myObject as new Object. You can now access all methods and properties of the left hand page (class). The class is completely separate and autonomous from your forms client code and so it easily extensible for future amendments without breaking other code elsewhere. You can create many left pages (classes) and many forms (right pages) without the two ever becoming dependant on each other. You can link any left and right page by instantiating objects in the forms client code where you wish to use the object.

The whole point i've found about the importance of OO is that you can easily end up with spaghetti code (all over the place with no structure). With OO, you are separating code as it relates to distinct actions on a form for example.

This snippet shows you the basics of using a Timer control on your form, creating a basic object from a class in your project and some looping to validate which numbers to display; so let's begin.

1. Create a new VB project [File/New Project] and choose [Windows Forms Application], name it what you want
2. In your solution explorer you should now have [My Project] & [Form1.vb]
3. Right click your project name in solution explorer (the one in bold) and add a class. Name it [Timer] and paste this code into the new Timer class:

'******************************************************************************************'
'****					   METHODOLOGY USED FOR CLASS DESIGN						  ****'
'****					   ---------------------------------						  ****'
'**** On every tick event, need to format the value so it's [HH:MM:SS:tenths] and	  ****'
'**** increment [m_TimerValue] by 1. Then set [m_FormattedTime] variable so it can be  ****'
'**** read by calling procedure in [MainForm] through its associated property.	   ****'
'******************************************************************************************'

Public Class Timer

'Private class variables (called fields). These are only accessible by methods inside the class!
	Private m_TimerValue As Integer
	Private m_FormattedTime As String
	Private m_Hour As Integer
	Private m_Minute As Integer
	Private m_Seconds As Integer
	Private m_Tenths As Integer

#Region "Property declarations"

	   'Use a public property so the forms client code can retrieve the data held in the above class fields. 
	   'Properties are a gateway to access class data!
	Public Property FormattedTime() As String
		Get
			Return m_FormattedTime
		End Get
		Set(ByVal value As String)
			m_FormattedTime = value
		End Set
	End Property

#End Region

#Region "Class constructor"

	'*** CLASS CONSTRUCTOR ***
		'When the object is first created in the forms client code, the [New] method is always invoked first; use this to 
		'set up the class variables, so we are forcing correct data into the properties. 
	Public Sub New()
		'Set [m_TimerValue] to 1 so the [FormatTime] method formats correctly on first loop.
		'If it's set to 0, then on first loop [m_TimerValue] isn't synced properly to the loop and
		'against [HH:MM:SS:tenths].
		m_TimerValue = 1
		m_FormattedTime = ""
		m_Hour = 0
		m_Minute = 0
		m_Seconds = 0
		m_Tenths = 0
	End Sub

#End Region

#Region "Format timer"

		'This method is called every time the [Timer] on the form 'ticks'. So if you set the timers interval to 1000, for
		'example (1second) then every second this class method is called. Because we want tenths of a second
		'to show, we set the timer interval to 100 = 0.1secs, i.e. the timer fires 10 times every second and when it
		'does we can work out which number in the [HH:MM:SS:tenths] to change, depending on the m_TimerValue
		'counter value.
	Public Sub TimerTick()

		FormatTime()
		m_TimerValue += 1

	End Sub

	Public Sub ResetTimerValue()

		m_TimerValue = 1

	End Sub

	Private Sub FormatTime()

		   'Waterfall conditional check. Basically the m_TimerValue is incremented by one every time the [TimerTick]
			   'is called above. If the value is less than 10 then it is just adds 1 to m_Tenths. If it equals 10 then we 
			   'have reached the end of tenths so we need to increase the seconds value by one and reset 
			   'm_TimerValue and m_Tenths to zero. Carry on doing this and if m_Seconds reaches 59 then we are 
			   'ready to increment the minutes value [m_Minute] by one; same happens when minutes reaches 59 and so
			   'now change the hour value. Carry on doing this if you want days, weeks, years, etc by nesting the 
			   'conditional 'trap' checks to see if values exceed the upper limit of the variable, e.g. minutes(59),
			   'hours(24), days(7), etc, etc.

		If m_TimerValue = "10" Then
			m_TimerValue = 0
			m_Tenths = 0
			If m_Seconds = 59 Then
				m_Seconds = 0
				If m_Minute = 59 Then
					m_Minute = 0
					If m_Hour = 59 Then
						m_Hour = 0
					Else
						m_Hour += 1
					End If
				Else
					m_Minute += 1
				End If
			Else
				m_Seconds += 1
			End If
		Else
			m_Tenths += 1
		End If

		'Convert to strings (as we are using a label or text box on the form. Determine if result of Hour, 
				'Minute or second is a single digit, if so then want each string to be two significant figures so Label.Text is 
				'same length. 

		Dim sHour As String = m_Hour.ToString
		Dim sMinute As String = m_Minute.ToString
		Dim sSecond As String = m_Seconds.ToString

		If sSecond.Length = 1 Then
			sSecond = "0" + sSecond
		End If
		If sMinute.Length = 1 Then
			sMinute = "0" + sMinute
		End If
		If sHour.Length = 1 Then
			sHour = "0" + sHour
		End If

		'Final format of Time String now available to 'client code'
		m_FormattedTime = sHour + ":" +  sMinute + ":" + sSecond + ":" + m_Tenths.ToString
		
	End Sub


	   'Can reset the digital clock on the form by calling this method.
	Public Sub ZeroHHMMSS()
		m_Hour = 0
		m_Minute = 0
		m_Seconds = 0
		m_Tenths = 0
	End Sub

#End Region

End Class



======================================================================

In your MainForm (Form1, for example) create a timer control by selecting it from the toolbox and dragging it to your form. It should appear in the bottom panel/container; set it's interval in properties box (on right) to 100. Now we can create an object of our timer class. Double click the form (in design view) and insert the Dim line:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
   Dim DigitalClock As New Timer()
End Sub



Put a Timer Control on the form and a label and use this line of code in the timer tick events (double click timer control):

Private Sub TimerControl_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerControl.Tick

	 label1.Text = DigitalClock.FormattedTime

End Sub




Hope that helps anyone trying to format time on their forms and more importantly using a basic class & object B)

This post has been edited by kryton46: 04 January 2009 - 05:39 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Basic Object/Class overview: Digital Clock example.

#2 Martyr2   User is offline

  • Programming Theoretician
  • member icon

Reputation: 5381
  • View blog
  • Posts: 14,289
  • Joined: 18-April 07

Re: Basic Object/Class overview: Digital Clock example.

Posted 03 January 2009 - 09:43 PM

If you flesh out the explanation a little more and build upon this I bet you would have yourself a nice little tutorial you can submit and get a contributor's badge. Then of course you can get kudos as well and have a shot at the thumb drive of the month contest.

:)
Was This Post Helpful? 0
  • +
  • -

#3 SHAEN   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 18-May 08

Re: Basic Object/Class overview: Digital Clock example.

Posted 12 April 2009 - 05:47 PM

hi i have just tried your example and it does not seem to work. the
'Dim DigitalClock As New Timer()' statement in the form part :
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
   Dim DigitalClock As New Timer() 
End Sub

does not work and so i moved it to the start of the form and then then
'label1.Text = DigitalClock.FormattedTime' was recognized but then when i run the form the label does not show the timevalue.
anyhelp?
Was This Post Helpful? 0
  • +
  • -

#4 kryton46   User is offline

  • New D.I.C Head
  • member icon

Reputation: 6
  • View blog
  • Posts: 44
  • Joined: 29-December 08

Re: Basic Object/Class overview: Digital Clock example.

Posted 12 April 2009 - 07:51 PM

View PostSHAEN, on 12 Apr, 2009 - 04:47 PM, said:

hi i have just tried your example and it does not seem to work. the
'Dim DigitalClock As New Timer()' statement in the form part :
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
   Dim DigitalClock As New Timer() 
End Sub

does not work and so i moved it to the start of the form and then then
'label1.Text = DigitalClock.FormattedTime' was recognized but then when i run the form the label does not show the timevalue.
anyhelp?


Hi Shaen,

I made a mess of the original tutorial, but with some great help from Jayman, we sorted out a few sloppy lines of code. The amended version is here.

p.s. i forget to mention that you need to add a button on the form, which starts the timer :rolleyes: So in design view, add from the toolbox i) label ii) button iii) timer control.

For reference, here's the exact code in my Form1:

 
Public Class Form1

	Private DigitalClock As New Timer()

	Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
		Label1.Text = DigitalClock.FormattedTime
		DigitalClock.TimerTick()
	End Sub

	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		Timer1.Enabled = True
	End Sub

End Class


Was This Post Helpful? 0
  • +
  • -

#5 dbasnett   User is offline

  • D.I.C Addict
  • member icon

Reputation: 121
  • View blog
  • Posts: 674
  • Joined: 01-October 08

Re: Basic Object/Class overview: Digital Clock example.

Posted 13 April 2009 - 06:56 AM

The code posted is not the best way to do a count up or down timer.

1. - The code is depending on the .Tick event to fire every 100 ms. If your entire program is just this timer that might be true, but if your program is doing a lot of other things this is a bad assumption.
2. - The class the OP created was named Timer. Doesn't .Net already have a class named Timer?
3. - The class is not self contained. It is dependent on other controls.

The OP should read about the StopWatch class.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1