【发布时间】:2014-06-01 11:25:02
【问题描述】:
我目前正在处理 Java 小程序的任务。这是作业:
使用数组创建一个列出您最喜欢的五首歌曲的小程序。小程序应该:
- 滚动歌曲标题列表,一次一个。
- 每首歌曲的标题都应该从小程序的顶部开始滚动到中间,然后从右侧滚动。
- 每首新歌的标题都应该以不同的颜色滚动。
- 小程序应该循环,也就是说,当它到达列表的末尾时,从列表的开头重新开始。
到目前为止,我的代码如下:
import java.applet.Applet;
import java.awt.*;
public class SongList extends Applet implements Runnable
{
String[] list = {"A - B", "C - D", "E - F", "G - H", "I - J"};
int counter = 0, xPos = 100, yPos = 0;
Color text_color = getRandomColor();
Thread runner;
public void start()
{
if (runner == null)
{
runner = new Thread(this);
runner.start();
}
}
public void run()
{
while (xPos < 220)
{
if (yPos < 100)
{
yPos += 2;
repaint();
try
{
runner.sleep(50);
}
catch (InterruptedException e) { }
}
else if (yPos == 100 && xPos != 220)
{
xPos += 2;
repaint();
try
{
runner.sleep(50);
}
catch (InterruptedException e) { }
}
else if (xPos == 220)
{
counter++;
xPos = 100;
yPos = 0;
}
}
}
public void paint(Graphics gr)
{
setBackground (Color.yellow);
gr.drawString(list[counter], xPos, yPos);
}
}
HTML 文件:
<html>
<body>
<applet code = "SongList.class" width = 200 height = 200>
</applet>
</body>
</html>
代码编译得很好,但是在上一首歌曲滚动出屏幕后,我找不到切换到下一首歌曲的方法。
我怎样才能做到这一点?
【问题讨论】:
-
感谢 Amal 的编辑。对不起,我很讨厌
-
1) 为什么要编写小程序?如果是由于规范。老师请发给Why CS teachers should stop teaching Java applets。 2) 为什么选择 AWT 而不是 Swing?请参阅我在 Swing extras over AWT 上的回答,有很多放弃使用 AWT 组件的充分理由。