【发布时间】:2016-12-12 22:13:23
【问题描述】:
我目前正在阅读 Head First C# 第三版,我正在使用 Visual Studio 2015 作为 IDE。书中的一个程序称为弹跳标签。
期望的结果: 在程序中,一个由 3 个标签对象组成的数组对应于表单上的按钮。当每个标签各自的按钮被按下时,标签应该从表单的一端移动到另一端,就像“弹跳”一样。
问题:标签移动到表单的右端,然后在表单的 3/4 处停止。他们永远不会反弹。图片见链接。 (rep 太低无法内联)
https://postimg.org/image/qn7s9pfdz/
一些技术细节: 表单有一个计时器,启用为 true 并且 Interval 为 1。假设计时器循环保镖数组,如果它们不为空,则调用它们的移动方法。
我已经包含了指向我正在学习的书中页面的链接。
我有一个 Bouncer 类的脚本和表单。
保镖类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bouncinglabels
{
using System.Windows.Forms;
class LabelBouncer
{
public Label MyLabel;
public bool GoingForward = true;
public void Move()
{
if (MyLabel != null)
{
if (GoingForward == true)
{
MyLabel.Left += 5;
}
if (MyLabel.Left >= MyLabel.Parent.Width - MyLabel.Width)
{
GoingForward = false;
}
}
else
{
MyLabel.Left -= 5;
if (MyLabel.Left <= 0)
{
GoingForward = true;
}
}
}
}
}
这是 Form1.Cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Bouncinglabels
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
LabelBouncer[] bouncers = new LabelBouncer[3];
private void ToggleBouncing(int index, Label labelToBounce)
{
if (bouncers[index]==null)
{
bouncers[index] = new LabelBouncer();
bouncers[index].MyLabel = labelToBounce;
}
else
{
bouncers[index] = null;
}
}
private void button1_Click(object sender, EventArgs e)
{
ToggleBouncing(0, label1);
}
private void button2_Click(object sender, EventArgs e)
{
ToggleBouncing(1, label2);
}
private void button3_Click(object sender, EventArgs e)
{
ToggleBouncing(2, label3);
}
private void timer1_Tick(object sender, EventArgs e)
{
for (int i = 0; i < 3; i++)
{
if (bouncers[i] != null)
{
bouncers[i].Move();
}
}
}
}
}
【问题讨论】:
标签: c# object parent-child