在每次循环迭代时添加新标签

时间:2017-02-01 14:57:27

标签: vb.net visual-studio-2015

我正在尝试制作一个刽子手应用程序,但无论出于什么原因我都无法得到这个词,你必须“猜测”才能正确显示。正如您在循环中看到的,每次迭代都会创建一个新标签。标签的text属性设置为wordString的字符,定义为wordLetter。设置新标签的所有属性后,将其添加到表单中,定义点以在标签下方绘制一条线,并使用xAxis(用于将下一个标签放置在前一个右侧)并迭代i。问题是,只有第一个标签显示,或者来自wordString“PROGRAM”的“P”。我相信这是因为每次迭代循环时,都会创建一个同名“wordLabel”的新标签,从而阻止创建新标签。我不知道怎么解决这个问题;即使我使用了数组,我仍然需要在每次迭代时制作一个新标签。

The result

Dim point1, point2 As Point

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim i As Integer

    Dim wordString As String = "PROGRAM"
    Dim wordLetter As String
    Dim xAxis As Integer

    Do While i < wordString.Length
        Dim wordLabel As New Label

        wordLetter = wordString.Chars(i)

        wordLabel.Font = New Font("Comic Sans MS", 25)
        wordLabel.AutoSize = True
        wordLabel.Text = wordLetter
        wordLabel.BackColor = Color.Transparent
        wordLabel.Location = New System.Drawing.Point(xAxis + 7, 190)

        Me.Controls.Add(wordLabel)

        point1.X = Convert.ToInt32(wordLabel.Location.X) - 10
        point1.Y = Convert.ToInt32(wordLabel.Location.Y) + 40

        point2.X = Convert.ToInt32(wordLabel.Size.Width) - 13
        point2.Y = Convert.ToInt32(wordLabel.Location.Y) + 40

        xAxis += 3
        i += 1

    Loop
End Sub

Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint

    e.Graphics.DrawLine(Pens.Black, point1, point2)

End Sub

1 个答案:

答案 0 :(得分:1)

这对你有用。 它保留了前一个标签的最后一个左侧位置。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Try
        BuildHangman("PROGRAM")
    Catch ex As Exception
        MessageBox.Show(String.Concat("An error occurred: ", ex.Message))
    End Try
End Sub

Private Sub BuildHangman(wordString As String)

    Dim i As Integer
    Dim wordLetter As String
    Dim lastLeft As Integer

    Dim sensibleFont As New Font("Segoe UI", 25)

    Do While i < wordString.Length

        Dim wordLabel As New Label

        wordLetter = wordString.Chars(i)
        wordLabel.Font = sensibleFont
        wordLabel.AutoSize = True
        wordLabel.Text = wordLetter
        wordLabel.BackColor = Color.Transparent
        wordLabel.Location = New System.Drawing.Point(lastLeft + 7, 190)

        Me.Controls.Add(wordLabel)

        lastLeft = wordLabel.Left + wordLabel.Width

        i += 1

    Loop

End Sub