我目前正在为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>
代码编译得很好,但是在上一首歌滚出屏幕后,我找不到改变下一首歌的方法。
我怎样才能做到这一点?
答案 0 :(得分:0)
else if (xPos == 220)
没用。 :)因为您使用的循环为219 xPos<220
,所以将其更改为xPos<=220
catch (InterruptedException e) { }
您正在吞咽Exception
以便正确编译,但您无法确定Exception
,请使用
catch (InterruptedException e) { e.printStackTrace();}
由于 1。 gr.drawString(list[counter], xPos, yPos);
无法在counter
中获得public void paint(Graphics gr)
。