Code:
package exepartone;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class assignment extends JApplet implements Runnable, ActionListener
{
int xPos, yPos;
JButton startStop;
Thread runner;
boolean isRunning = true;
ImageIcon birdIcon;
private AudioClip sound1;
JButton playSound, loopSound, stopSound;
public JComboBox chooseOption;
int val = 0;
public void init()
{
Dimension size = getContentPane().getSize();
Container contentPane = new AnimationPane();
setContentPane(contentPane);
contentPane.setBackground(Color.white);
contentPane.setSize(size);
xPos = contentPane.getSize().width/2;
yPos = contentPane.getSize().height/2;
startStop = new JButton("Stop");
contentPane.add(startStop);
startStop.addActionListener(this);
Container c = getContentPane();
c.setLayout(new FlowLayout());
String choices[] = {"Bird", "Leak"};
chooseOption = new JComboBox(choices);
chooseOption.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
val = chooseOption.getSelectedIndex() == 0 ? 0 : 1;
sound1.stop();
}
});
c.add(chooseOption);
ButtonHandler handler = new ButtonHandler();
playSound = new JButton("Play");
playSound.addActionListener(handler);
c.add(playSound);
loopSound = new JButton("Loop");
loopSound.addActionListener(handler);
c.add(loopSound);
stopSound = new JButton("Stop");
stopSound.addActionListener(handler);
c.add(stopSound);
sound1 = getAudioClip(getDocumentBase(), "leak.wav");
birdIcon = new ImageIcon(getImage(getCodeBase(), "bird.gif"));
}
public void start()
{
if (runner == null)
{
runner = new Thread(this);
runner.start();
}
}
public void stop()
{
runner = null;
}
public void run()
{
while (isRunning)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException e) { }
xPos += changeBy();
yPos += changeBy();
repaint();
}
}
int changeBy()
{
double myVal;
if (java.lang.Math.random() < .5)
{
myVal = java.lang.Math.random() * -10;
}
else
{
myVal = java.lang.Math.random() * 10;
}
return (int) myVal;
}
public void actionPerformed(ActionEvent e)
{
if (isRunning)
{
isRunning = false;
startStop.setText("Start");
stop();
}
else
{
isRunning = true;
startStop.setText("Stop");
start();
}
}
class AnimationPane extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (val == 0)
birdIcon.paintIcon(this, g, xPos, yPos);
}
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (val == 1)
{
if (e.getSource() == playSound)
sound1.play();
else if (e.getSource() == loopSound)
sound1.loop();
else if (e.getSource() == stopSound)
sound1.stop();
}
}
}
}
