13
Paint the window and play a sound in a loop
Download the background image and the audio file.
Copy bluewave.jpg in a folder called images and loop.au in a folder called sounds.
- Java/Canvas
- Canvas.java
- images
- bluewave.jpg
- sounds
- loop.au
Edit Canvas.java.
- // <applet code="Canvas" width="500" height="300">
- // <param name="background" value="images/bluewave.jpg"/>
- // <param name="sound" value="sounds/loop.au"/>
- // </applet>
- import java.applet.*;
- import java.awt.*;
- import java.awt.event.*;
- public class Canvas extends Applet implements MouseListener {
- private Image image;
- private AudioClip sound;
- private Boolean playing = false;
- private int imageWidth, imageHeight;
- public void init() {
- String p;
- p = getParameter("background");
- if (p != null) {
- MediaTracker tracker = new MediaTracker(this);
- image = getImage(getCodeBase(), p);
- tracker.addImage(image, 0);
- try {
- tracker.waitForID(0);
- }
- catch (InterruptedException e) {
- }
- imageWidth = image.getWidth(this);
- imageHeight = image.getHeight(this);
- }
- p = getParameter("sound");
- if (p != null) {
- sound = getAudioClip(getCodeBase(), p);
- playing = true;
- }
- addMouseListener(this);
- }
- public void mouseClicked(MouseEvent e) {
- if (playing)
- stop();
- else
- start();
- playing = !playing;
- }
- public void mouseEntered(MouseEvent e) {}
- public void mouseExited(MouseEvent e) {}
- public void mousePressed(MouseEvent e) {}
- public void mouseReleased(MouseEvent e) {}
- public void paint(Graphics g) {
- int width = getSize().width;
- int height = getSize().height;
- int y = 0;
- while (y < height) {
- int x = 0;
- while (x < width) {
- g.drawImage(image, x, y, this);
- x += imageWidth;
- }
- y += imageHeight;
- }
- }
- public void start() {
- if (sound != null)
- sound.loop();
- }
- public void stop() {
- if (sound != null)
- sound.stop();
- }
- }
$ javac Canvas.java
$ appletviewer Canvas.java
The image is replicated to cover the entire background of the window. Try resizing it. You should also be hearing a sound loop. Click in the window to pause the player. Click again to restart it.
Comments