我目前正在阅读 Head First C# 第三版,我正在使用 visual studio 2015 作为 IDE。书中的一个程序叫做弹跳标签。
期望的结果: 在程序中,一个包含 3 个标签对象的数组对应于表单上的按钮。当每个标签各自的按钮被按下时,标签应该像“弹跳”一样从表单的一端移动到另一端。
问题:标签移动到表单的右端,然后在表单的 3/4 处停止。他们永远不会反弹。请参阅图片链接。 (代表太低无法内联)
https://postimg.org/image/qn7s9pfdz/
一些技术细节:该表单有一个计时器,它被启用为true并且Interval为1。假设计时器循环保镖数组,如果它们不为空,则调用它们的 move 方法。
我已经包含了指向我正在学习的书中页面的链接。
我有一个保镖类的脚本和表单。
保镖类
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();
}
}
}
}
}
最佳答案
这应该有效。刚刚将您的 else 语句向上移动。你的 else 低于你的 if with MyLabel != null。
namespace Bouncinglabels
{
using System.Windows.Forms;
class LabelBouncer
{
public Label MyLabel;
public bool GoingForward = true;
public void Move()
{
if (MyLabel != null)
{
if (GoingForward)
{
MyLabel.Left += 5;
}
else
{
MyLabel.Left -= 5;
if (MyLabel.Left <= 0)
{
GoingForward = true;
}
}
if (MyLabel.Right >= MyLabel.Parent.Width)
{
GoingForward = false;
}
}
}
}
}
关于C# 试图使标签(对象)从表单的一侧反弹到另一侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41101763/