Home
Email
Butnz!

Image Canvases and Buttons

About the first thing any Java programmer wants to do that is not a matter of finding it in the AWT is to put an image on his (or her) applet. This is easy once you find out you have to extend from Canvas and draw it yourself, but you still have to sort out the intricacies of paint(), update() and repaint(). Essentially what happens is whenever your window needs to be repainted, update() is called with a Graphics which tells you what sort of output device you're working with, and what needs to be updated. By default, update() paints the area in the background colour, and then calls paint() with the same Graphics to do the real work. If you want to force a repaint of the component, you can just call repaint() yourself, or repaint(100) to specify "repaint this within 100 milliseconds".

A programmer will typically also want to get away from the ugly gray buttons provided by the Java Virtual Machine implementation, and do some cool ones instead. This is almost the same thing as putting an image on the screen, except you need to detect when the user clicks on it, and give some visual feedback so the user knows they were heard. The ImageCanvas class provides both of these functions, making it trivial to write a simple slide viewer like this one which shows you some of the images used on this site.

Why are you looking at this without Java?

There are three ImageCanvases in this applet. The big yellow one at the top is just given an image whenever we want it changed. The two buttons at the bottom are ImageCanvases which have been told to report back to the applet whenever they're clicked on. At the same time, they switch over to a second image for 200 milliseconds. By the way, Graphics.drawImage does recognise transparent colours in GIFs.

The ImageCanvas is compatible with the JDK 1.02 event model, in particular when acting as an image button it will call mouseDown in its event handler. The preferredSize() of the ImageCanvas is the size of the primary image.


This page hosted by Get your own Free Home Page.
This page uses Verdana fonts which Windows users can download from Microsoft for free.
Background pattern by Net Creations.
"Next" and "Previous" icons from Caboodles.
1