使用Java Applet Loop在前一个歌曲滚出屏幕后切换到下一首歌曲

时间:2014-06-01 03:12:20

标签: java applet

我目前正在为Java小程序分配工作。这是作业:

使用数组创建一个列出五首喜欢的歌曲的小程序。小程序应该:

  • 一次滚动歌曲标题列表。
  • 每个歌曲标题应从小程序的顶部开始,然后滚动到中间,然后向右滚动。
  • 每首新歌曲标题都应以不同的颜色滚动。
  • applet应该循环,也就是说,当它到达列表的末尾时,在列表的开头重新开始。

到目前为止,我的代码如下:

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>

代码编译得很好,但是在上一首歌滚出屏幕后,我找不到改变下一首歌的方法。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

  1. else if (xPos == 220)没用。 :)因为您使用的循环为219 xPos<220,所以将其更改为xPos<=220
  2. catch (InterruptedException e) { }您正在吞咽Exception以便正确编译,但您无法确定Exception,请使用

    catch (InterruptedException e) { e.printStackTrace();}

  3. 由于 1。 gr.drawString(list[counter], xPos, yPos);无法在counter中获得public void paint(Graphics gr)