Using pictures in applets
Just like "adding" sound files to an applet you can add pictures. Now I want to explain to you how to do this by adding a background picture to our "ball bounce" applet. Again we have to declare an instance variable, an Image object called backImage:
Then we load a picture to our applet and store it in the object reference backImage (import java.applet.* and java.net.*!!). This works very similar to loading sound files, please add these lines to your init() - method:
// load file Land.jpg
backImgage = getImage (getCodeBase (), "Land.jpg");
As a last step we have to paint this picture in the paint() - method of the applet:
// drawing the image: g.drawImage (name, x- value, y - value, frame)
g.drawImage (backImage, 0, 0, this);
That's it! I used a *.jpg - file in this example but that is not that good. Normally you should use *.gif - files, because their size is not that big, (makes the applet run faster), and they are more common in the internet. Another reason to use *.gif - files is that you can define the background of a *.gif - file transparent. So you can use them to overlay for example a ball object (which is just a colored circle at the moment) with a real good looking picture. You can see a example for this in the game Streethockey and maybe there will be a "advanced topic" for this technique someday!
Sourcecode download
Take a look at the applet
Next chapter
Handling mouse events
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.
|