Morris Hirsch Java Techniques Pages

By way of thanks for all the great resources I have found on the Web, I would like to share some Java techniques and examples that may save you some time and trouble. These are all things that I had to do, and that took me a while to figure out.
Testing...
Make sure we can do the easy stuff first... Run a Hello Applet, trying both 1.0 and 1.1 versions of Java.

Most of the following examples require the 1.1 version of Java, but some work with 1.0 forward. Some have been back-fit to 1.0 and some others could be with a little effort, but some could not.

Doodle, a Simple Drawing Program
What do computer programmers do? I wrote this page as a visual aid, and used it when I spoke at Career Day at my daughter's school. It runs a simple drawing applet, and also shows the source code. Today's kids being pretty familiar with computers, they pointed out a bunch of features it was lacking. I decided to grow this into a set of pages, adding the requested features, and hopefully showing something of the development process. Doodle is taken from the DoodlePad example in Exploring Java, by Patrick Niemeyer and Joshua Peck, first edition copyright 1996 by O'Reilly and Associates. Written for use with either 1.0 and 1.1 versions of Java.
Printing.
Support for printing was absent in Java 1.0, added in 1.1, but with a number of bugs, both in the concept and implementation.
I have been able to work around these problems, with the aid of some code classes that others have written, copyrighted, and generously shared with the public. You can produce files in format, of all or part of your Java application screen, or of any off-screen drawing not shown on screen.
I am trying to make these classes better known, by providing an example of their use, and also providing some additional useful code of my own.
Here is a recent addition, Portable Network Graphics (PNG) encoder.
ListenerAdder
The 1.1 event model is more flexible, but arguably harder to use than the earlier model. It encourages the use of anonymous classes as handlers, rapidly increasing the number of classes in a directory. An alternative style is to use a ListenerAdder helper class, which adds all relevant listeners for all components. This lets you write less code, have less class files to manage, and have faster loading.

A similar technique is described in Chapter 3, "Event Adapters," of the O'Reilly book, "Developing Java Beans" by Robert Englander. A very nice book.

WrapLayout.
The AWT FlowLayout has a known bug that sometimes causes it to hide some components. The bug has been around so long that some call it a feature, which of course it is not! This fully compatible WrapLayout.java entension overrides one method, which corrects that bug.
StraightLayout (Custom Layout Manager).
All the books explain the standard managers, and conclude by saying that you can also build your own. You can indeed, and here I offer a useful (to me anyway) one, StraightLayout.java to prove it. It lets you size components "the same as" another, reference component, even though the reference is not under the same layout. Handy for keeping sizes inside two Panels in step, for example fixed headers and scrolling columns. No demo here, just the source.
Gridbag Helper.
The Gridbag Layout is infamous for its difficult API, but offers many advantages in use. This helper class tames the API, by wrapping it in several convenient methods. This is a work-in-progress, with methods implemented as I needed them. No demo here, just the source.
Data Compression Algorithms
Two common data compression techniques, Limpel Ziv Welch (LZW), and Run Length Encoding (RLE), implemented as classes. No demo here, just the sources, but they include test / demo code.

Be advised that these, and virtually all data compression techniques, have been granted patents. You may have your opinion about that, as I certainly have mine.
This software uses only algorithms and coding techniques that are available to the public in the open literature. You are however, advised to make your own determination of legality, for your intended use.

Capturing Console Output
This from the good folks at Sun, the Java Developers Connection. If you don't yet subscribe to JDC you should -- it's free.

This tip demonstrates how you can record in a log file everything printed to standard out and standard error. This is especially useful if you deploy an application and your users encounter problems. You can have the users send you the log file for analysis.

A SaveOutput object is a PrintStream object that acts like a tee. Any characters it receives are forwarded to two places: the log file and the underlying print streams. It records everything printed to standard out and standard error, not only by your own classes, but by any core or third-party classes.

MultiFilter.java
MultiFilter extends the awt.RGBImageFilter class, with convenience methods for processing an Image to: No demo here, just the source.
Popup Menu Helper.
The Popup Menu API is less than obvious. Again, a helper class makes it easier to use. The Popup Menu works well off some AWT classes, but has problems when anchored to others. This demo shows what works and what does not.
Balloon Help Helper.
The AWT does not provide balloon help, although the newer Swing toolkit does. This BubbleHelper.java helper class lets any of your AWT GUI components have balloon help. It does require the 1.1 event model.
Picture Buttons.
The AWT does not provide picture buttons, but the excellent book Mastering the AWT by David Geary shows how they can be implemented. I provide some extensions to these classes, and examples of their use.
I also provide an animated button class, in which the button face is a custom drawing, such as a clock face or gauge, that is provided (and may be updated at any time) by the application.
Extending Hashtable
The Hashtable class provides key-value mapping between generic Objects. It is most useful if subclassed to provide mapping between keys and values of classes suitable for your problem. Here are two examples:
HashLink.java
Map each key to an extensible list of values rather than one.
HashWeight.java
Map each key to a weight that can be incremented and tested.
And a cautionary note -- we tend to think of String as the only suitable key class, but almost any class will do. A notable exception is Point and any extension classes. Your extension constructor will create a Point (0, 0) every time, and they will all have the same hashCode. Beware Rectangle for the same reason. To prevent this problem, your key class must override the int hashCode () method.
Cursor Panel.
CursorPanel extends Panel, providing one or more overlay cursors, which either the program or the user may position, to select data from places in the Panel display.
Off Screen Buffer Animation.
Animation using an Off Screen Buffer, and faster painting without the paint () method. Works for 1.0.2 and newer Java.
Starfield.
A StarField shows a two-dimensional field of markers, each representing a data point of some kind. By selectively showing or hiding some of the markers, a starfield can show two-dimensional "slices" from higher-dimension data. Sliders (or other controls) let a starfield show regions of the data.

A StarField is a natural choice for geometric (or geographic) data; the earliest applications displayed restaurants, real estate for sale, and incident reports for a community service organization, according to user selection criteria.

BarDial and BarControl.
BarDial extends Component to draw a bar chart, BarControl extends BarDial to provide mouse response, so the user can resize bar sectors. In other words, a GUI slider with multiple sections. Use it to control your heating and airconditioning.
PieDial and PieControl.
PieDial extends Component to draw a pie chart, PieControl extends PieDial to provide mouse response, so the user can resize pie sectors. In other words, a GUI knob or rotary slider with multiple sections. Use it to control your sailboat autopilot.
Click! Oh, never mind...
No example yet for this one, but worth a mention even so. Say you have a GUI with a few TextFields and Buttons, and you listen for focusLost on the TextFields, to be advised of "entries" when a user tabs out to the next one. Further say that some values in TextFields may disable some Buttons.

Now your user clicks into a TextField, types a few characters into it, then clicks a Button. Clicking on the Button causes focusLost on the TextField, you handle it and decide the incomplete value is such that you disable some Buttons, including the one that the user clicked on, and the Button Click is never delivered.

That's right, the Button was enabled when your user clicked on it, and the AWT visuals show it going down and up, but the ActionEvent never comes to you. Just letting you know it can do this.

The HTML Form Toolkit
C code (not Java!) that helps you write CGI programs, which can serve and then process HTML Forms. I wrote all this a few years ago, to support CGI access to legacy systems written in C. If you would like to port this code to Java, go right ahead.
See also a more "industrial strength" Tom Boutell's CGIC Library
For a newer approach, see the PHP and Perl home pages.
Project Principles, Software or Otherwise
Not code but thoughts about writing code for a living. These are all pretty obvious, yet easy to forget at times. That's why the first one says "Write things down."

Sources for Everything (maybe)

This software is provided free of charge with no support. Email me at morris_hirsch@brown.edu if you do have a problem, and I will try to help, but I cannot promise to.

Your comments, suggestions, bug reports, bug fixes, and enhancements, are welcome!

Was this Helpful?

Was this Helpful? Was it what you were looking for? Suggestions? How did you find this page? Search result, following a link, recommendation? Please let me know. Email me at morris_hirsch@brown.edu

Actually, I'm happy right here.

Who is this guy? I have been programming for so long, "I remember when IBM machines were called Univacs" and I still enjoy doing it. Please also visit my home page.

Legalities

Except for all sections which are identified as the work, and copyright, of others, this work is Copyright (C) 1998 by Morris Hirsch. All rights reserved, except as granted here.

Your basic Coplyleft terms -- Redistribution and use in source and binary forms, with or without modification, for any purpose, are permitted, except as may be restricted by original copyright holders, provided that the following conditions are met:

DISCLAIMER

This software is provided free of charge with no support. By use of this free information you agree to waive any claims, for any damages whatsoever, regardless of the fact that some states do not allow the exclusion, or limitation, of liability for consequential or incidental damages.
These works are essentially lengthy examples of some known techniques, and are presented with the same rights and limits as book examples. This software is provided in source format; You are advised to examine it and understand it, before putting it to use.
This information could include technical inaccuracies or typographical errors. Changes may be periodically added to the information herein, at any time without notice.
This software uses only algorithms and coding techniques that are available to the public in the open literature. You are however, advised to make your own determination of legality, for your intended use.
All of the web sites linked from this Site have been viewed, but they are not reviewed periodically, and may have changed. The Author is not responsible for, and has no control over, the content of any off-site pages, or any other web sites linked to from them. Therefore, a link to a web site does not mean endorsement, or accept any responsibility for the content of such site. It is your responsibility to take precautions, to ensure that whatever is selected is free of viruses, worms, Trojan horses, and other items of a destructive nature.
This software is provided by the Author and Contributors ``AS IS'' and any express or implied warranties, including, but not limited to, non-infringement, and the implied warranties of merchantability and fitness for a particular purpose, are disclaimed.
In no event shall the Author or Contributors, or their Agents or Servants, be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.
No animals were used in the testing of this software, I did all the suffering myself.
If you become dizzy or develop a headache while reading this code, discontinue use immediately. Do not study this code while driving, or operating heavy machinery.
1