I'm self-studying computer science for enrichment, and I have to say the first thing I gained was a new-found respect for this field and those in it. With that said, I'm so dang confused on my last homework problem that concerns applets. I would appreciate any help I can get. But I'm sure what's hard for me is simple for you hehe.
The question asks to make an applet emulating a banner ad. The ad should display a message alternating "East or West" and "Java is Best" every 2 seconds.
Here is the prototype code I've been given:
// This applet displays a message moving horizontally
// across the screen.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Banner extends JApplet
implements ActionListener
{
private int xPos, yPos; // hold the coordinates of the banner
public void init()
{
Container c = getContentPane();
c.setBackground(Color.WHITE);
xPos = c.getWidth();
yPos = c.getHeight() / 2;
Timer clock = new Timer(30, this); // fires every 30 milliseconds
clock.start();
}
// Called automatically after a repaint request
public void paint(Graphics g)
{
super.paint(g);
g.drawString("Hello, World!", xPos, yPos);
}
// Called automatically when the timer fires
public void actionPerformed(ActionEvent e)
{
Container c = getContentPane();
// Adjust the horizontal position of the banner:
xPos--;
if (xPos < -100)
{
xPos = c.getWidth();
}
// Set the vertical position of the banner:
yPos = c.getHeight() / 2;
repaint();
}
}
Here are the hints the book includes (they didn't help me much
)
At the top of your class define a variable that keeps track of which message is to be displayed. For example, private int msgID = 1;
In the method that processes the timer events, toggle msgID between 1 and -1: msgID = -msgID
Don't forget to call repaint.
In the method that draws the text, obtain the coordinates for placing the message:
Container c = getContentPane();
int xPos = c.getWidth() / 2 - 30;
int yPos = c.getHeight() / 2;
Then use a conditional statement to display the appropriate message:
if (msgID == 1)
{
...
}
else // if msgID == -1
{
...
}
THANK YOU AGAIN FOR YOUR HELP!