I am writing a program for a class where I need to have the american flag scale the flag pole to the national anthem. I have the code but get an error that the applet is not found even though its there. I am using eclipse. Can anyone help me with what I am missing?
Thanks in advance...
Code:
@SuppressWarnings("serial")
public class Lab5b extends JApplet {
private AudioClip audioClip;
public Lab5b() {
add(new ImagePanel());
URL urlForAudio = getClass().getResource("audio/us.mid");
audioClip = Applet.newAudioClip(urlForAudio);
audioClip.loop();
}
public void start() {
if (audioClip != null) audioClip.loop();
}
public void stop() {
if (audioClip != null) audioClip.stop();
}
/** Main method */
public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("Lab 5");
// Create an instance of the applet
Lab5b applet = new Lab5b();
applet.init();
// Add the applet instance to the frame
frame.add(applet, java.awt.BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Display the frame
frame.setSize(200, 660);
frame.setVisible(true);
}
}
@SuppressWarnings("serial")
class ImagePanel extends JPanel {
private ImageIcon imageIcon = new ImageIcon("image/us.gif");
private Image image = imageIcon.getImage();
private int y = 550;
public ImagePanel() {
Timer timer = new Timer(120, new TimerListener());
timer.start();
}
class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
increaseY();
}
}
public void increaseY() {
if (y > 0) {
y--;
repaint();
}
}
/** Draw image on the panel */
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
g.fillRect(0, 0, 10, 660);
g.drawImage(image, 11, y, 160, 84, this);
}
}
}
Several things to note
Applets
do not begin execution at main()
method. However, it is
possible to execute the applets
by using the Java interpreter (by
using the main()
method) if you extend your class
with Frame
.
It is important to have the init()
method since it is called by the
browser or applet viewer to inform this applet that it has been
loaded into the system. It is always called before the first time
that the start method is called.
JFrame
and JApplet
are all top level containers and instead of
adding the applet
to the frame
, i would rather create an object
of JPanel
since it can be added to both JFrame
/JApplet
. In your
case just add ImagePanel
to either of the top level container.
I/O Streams do not provide much scope for applets
.
It is not possible for an applet
to access the files on the users
hard disk.
Read more here