【问题标题】:Change to the next song after the previous one scrolls out of the screen using Java Applet Loop使用 Java Applet Loop 在上一首歌曲滚动出屏幕后切换到下一首歌曲
【发布时间】: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>

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

我怎样才能做到这一点?

【问题讨论】:

标签: java applet


【解决方案1】:
  1. else if (xPos == 220) 没用。 :) 因为您使用循环高达 219 作为 xPos&lt;220 所以将其更改为 xPos&lt;=220
  2. catch (InterruptedException e) { } 你正在吞食Exception 以便它正确编译但你不会确定Exception 所以使用

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

  3. 并且由于 1. gr.drawString(list[counter], xPos, yPos); 无法在 public void paint(Graphics gr) 中得到正确的 counter

【讨论】:

  • 感谢您的回答!我想我通过将 while (xPos
  • while(true) 也会解决您的问题,但更具体一点,正如我所说的,(xPos &lt;= 220) 也会这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多