In Visual Basic, simulate a traffic light with three small square text boxes placed vertically on a form. Initially, the bottom text box is solid green and the other text boxes are dark gray. When the Tab key is pressed, the middle text box turns yellow and the bottom text box turns dark gray. The next time Tab is pressed, the top text box turns red and the middle text box turns dark gray. Subsequent pressing of the Tab key cycles through the three colors. Hint: First place the bottom text box on the form, then the middle text box, and finally the top text box.
Design the Interface:
First we need to design the interface. The following image shows an example of what the form might look like when the program runs.
For this program, it is important to place the text boxes in the order that you want them to gain focus. In real life, a traffic light is green, then yellow, then red. So we need the focus to start with the bottom text box and move up to the middle box, and then finally the top. The easiest way to accomplish this task is to place the bottom text box first, then the middle, then the top.
Suggested Control Names and Attributes:
Name Property | Text Property | Control Type | Notes |
frmTrafficLight | Traffic Light | Form | Holds Controls |
txtRedLight | Text Box | Red Light. | |
txtYellowLight | Text Box | Yellow Light. | |
txtGreenLight | Text Box | Green Light. |
Write the Code:
' Project: Traffic Light ' Programmer: Your Name Here ' Date: April 16, 2014 ' Description: Simulates a traffic light with three text boxes. When the program starts, the bottom text ' box is green and the others are gray. When the user presses the tab button, the focus changes ' causing the light to turn yellow and red. Public Class frmTrafficLight Private Sub txtGreenLight_GotFocus(sender As Object, e As EventArgs) Handles txtGreenLight.GotFocus txtGreenLight.BackColor = Color.Green End Sub Private Sub txtGreenLight_Leave(sender As Object, e As EventArgs) Handles txtGreenLight.Leave txtGreenLight.BackColor = Color.DarkGray End Sub Private Sub txtRedLight_GotFocus(sender As Object, e As EventArgs) Handles txtRedLight.GotFocus txtRedLight.BackColor = Color.Red End Sub Private Sub txtRedLight_Leave(sender As Object, e As EventArgs) Handles txtRedLight.Leave txtRedLight.BackColor = Color.DarkGray End Sub Private Sub txtYellowLight_GotFocus(sender As Object, e As EventArgs) Handles txtYellowLight.GotFocus txtYellowLight.BackColor = Color.Yellow End Sub Private Sub txtYellowLight_Leave(sender As Object, e As EventArgs) Handles txtYellowLight.Leave txtYellowLight.BackColor = Color.DarkGray End Sub End Class