I'm currently working on an assignment for Java applets. This is the assignment:
Use arrays to create an applet that lists five of your favorite songs. The applet should:
- Scroll the list of song titles, one at a time.
- Each song title should start at the top of the applet and scroll to the middle then, scroll off the right hand side.
- Each new song title should scroll in a different colour.
- The applet should loop, that is, when it gets to the end of the list, start over again at the beginning of the list.
So far, my code is as follows:
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 file:
<html>
<body>
<applet code = "SongList.class" width = 200 height = 200>
</applet>
</body>
</html>
The code compiles fine but the I can't find a way to change to the next song after the previous one scrolls out of the screen.
How can I achieve that?