Free Source Code

Here are a few useful bits of free source code. You're completely free to use them for any purpose whatsoever. All I ask is that if you find one to be particularly valuable, then consider sending feedback. Please send bugs and suggestions too. Enjoy


Android Code

Flow Layout

The Android SDK is missing a number of useful facilities found in the more mature Swing libraries, and one of the most basic is the humble FlowLayout manager. Implemented as an Android utility class, this is implemented as a View container that arranges its children from left to right, wrapping onto new lines as needed.

    View the code

Activity Heartbeat

Similar to the javax.swing.Timer class, this class is perfect for when you want to repeatedly run a background task at some frequency while a given Activity is active such as polling a server and updating the screen to reflect server changes.

    View the code


Java Code

The links following each Java implementation show HTML versions of the code with syntax highlighting which were generated using the Java to HTML utility below. The simplest way to download one as a .java file is to view the page and copy & paste the text from your browser into a .java file.

Login Panel

A simple yet complete log-in/log-out panel with user callbacks for approving log-in attempts and getting notification of log-outs.

    View the code

Password Changer

A simple dialog that allows users to enter their old password and to request a new one using a callback to validate or reject user entries.

    View the code

Property Manager

Are you constantly driven nuts by all the different sources of properties used within your large Java projects including command line arguments, user preferences, environment variables, defaults, etc.? This class allows you to collect and access them from one convenient location so that the code that needs the properties doesn't need to know where they came from. Supports persistence of user preferences.

    View the code

Selection Coordination

Share instances of this class among several parts of your code that need to coordinate on some sort of “Selected” object. Each such code section can change the currently selected object (usually due to user selection events) and they can add selection listeners to stay informed of changes made by other code sections. JDK 1.5 generics made it possible to create this surprisingly simple yet powerful utility.

    View the code

Object Pair

Container for two objects. Similar to the Pair class in the C++ STL libraries.

    View the code

Static Utilities

A large collection of generally useful Swing utilities.

    View the code

Icon Utilities

A few static methods and classes for dealing with icon resources.

    View the code

Safe Object Streams

Java helper class that safely creates pairs of ObjectInput/OutputStream objects. This process requires a tricky bit of client/server handshaking to set up. The purpose of this class is to make this a safe and easy process.

    View the code

JarLoader

Java class able to load all the jar files in a given directory containing classes of a given type. It can also be set to continuously track that directory for new jar files that are added later.

    Viewthe code

Component Dependency Handler

Ever pull your hair out tracking down why some GUI component is not enabled or disabled when it should be? Or visible or invisible, etc? Sometimes the rules for knowing under exactly which combinations of application state should affect a given component can get quite complicated, and creating listeners with complex if/else blocks often result which need constant fixing. Well, there's a better way to manage all those state changing rules. Rather than trying to figure out all the possible components that might be affected by a given component state change and trying to set their states directly, you can create dependency graphs that describe which components are dependent on which others and then enforce those dependencies through the use of the ComponentDependencyHandler class. An object of this class represents all the dependencies of one component's particular state upon one or more other components. See the description and example code in the source file for details.

    View the code

Infinite Binary Tree

Here is a good Java example of one important way to create JTrees. This a tiny Java test program has some surprisingly interesting behavior. It creates a JTree with an infinite number of internal nodes and no leaf nodes! Each internal node is labeled with a unique positive integer such that every positive number can be found if you know where to look. The basic concept demonstrated is use of the TreeModel class to display hierarchically structured information that may be huge or expensive to access--for example, data in a database.

    View the code

java2html

You can find lots of converters by the same name with a quick Google search on the term "java2html" but most are way more complex than needed. I weeded through dozens and found this little gem which was small but effective. I did expand on it a bit and think it's quite useful. Click the following link to see the result of running java2hml.java on itself. All of the Java links on this page were formatted using this tool.

    View the code

FloatSlider

This subclass of Scrollbar operates with floating point ranges and values useful for situations in which integer values are not appropriate. A constructor flag allows specification of either linear or log ranges. Written using only JDK 1.1 to allow it to be used in Applets. See the Retirement Calculator Applet for a working example of FloatSlider using bother linear and log ranges.

    View the code

Axis

Choosing nicely rounded tic labels for graph axis drawing is a very difficult problem. This utility collects some found code with my own ideas to create the truly general methods I'd longed for over many years. Includes a static function for selecting and labeling graph axis tic labels for both linear or log scales. Given a numeric range and a maximum number of tics, this class can produce a list of labels with the nicest round numbers not exceeding a given maximum number of labels. A high-level static method is also provided to compute and draw an axis into a given AWT Graphics object. An example main method uses two FloatSlider objects that the user can adjust to choose a numeric range and which then uses the drawing method to draw labeled graph axes for the dynamically changing range.

    View the code

BarChart

A high-level component implementing a bar chart panel with labeled axes and full selection support.

    View the code

Time Picker

Presents two or more selectable dates arrayed on a timeline. Useful for at-a-glance visualization of potentially large collections of time stamps making it easy to see how they cluster. Presents well chosen shading and tick marks from month granularity down to minutes with labels as they fit.

    View the code

ZoomWindow

A JFrame that presents a given image that can be stretched and shrunk by the user without changing the image aspect ratio.

    View the code

SelectionSet

Similar to Selection class but for operates on a "set" of objects and notifies SelectionSetListenersof set membership changes. Useful as a central container for coordinated selection between a group of viewer/listeners.

    View the code

Inlay

A container similar to javax.swing.Box in that it lays out added components along a given axis. What it adds are visual borders, alternating color backgrounds for nested Inlay components, a selection model, and a tree traversal method.

    View the code

TrieMap

A clean implementation of the Trie associative array data structure. See the Wikipedia pag e for the full description. In short, this is a container that associates String keys with user data with very fast insertion, retrieval and deletion. Binary trees and hash tables have O(log n) operations with n proportional to the number items stored and have some poor worst case performance, whereas trie operations run in essentially O(m) linear time where m is proportional to the key string length independent of the number of elements stored. Note: Unlike most utilities here, this one has not been battle-tested in a commercial product. Also it is probably not a good replacement for the many excellent core Java Collection implementations. It is probably most useful as an example or perhaps a good starting point for porting to other languages and platforms.

    View the code

WeakProxyReference

Solves a common and nasty memory leak problem where the act of adding a listener or other event handler to one object creates a hard reference to whatever objects it operates on causing those objects to never be garbage collected. A common example is adding a listener to a button or other component in one frame which does something to another frame (or some sub-component in within it). Even though that second frame may be set to dispose on close and the application doesn't contain any hard references to it, that frame will never be garbage collected due to the fact that the listener knows about that frame. In other words, the mere fact that a listener knows about (i.e. does something to) an object creates an implicit hard reference to that object. The obvious solution to the problem is to track down all such listeners and remove them (letting them be garbage collected) when the window they control is being closed. In practice this is extremely awkward to do and is very error prone. Forgetting to remove a single listener can cause large amounts of memory to never be reclaimed.

The ideal solution would be a way to add a listener without having to worry about when remove it and for any objects it operates on to be properly garbage collected when there are no other references to it. This utility class contains a static method that allows the caller to "set and forget" any listener you wish to add to any component without having to worry about removing it at the proper time.

    View the code

StackMethodExtractor

Note: This utility is made obsolete in JDK 1.4 and beyond by the addition of Throwable.getStackTrace(). This is now only useful in situations where JDK 1.4 is not available or acceptable.
This utility contains a static method which returns the full name of the method a given number of stack frames above the calling method Click following link to see the code. It's magic.

    View the code


C & C++ Code

R-Trees

Implementations of the R-Tree algorithm by Toni Gutman. R-Trees provide Log(n) speed rectangular indexing into multi-dimensional data. Based on his original implementation, I brought it up to date with ANCI specifications and added a nice fix for a degenerate case based on sphere volumes. Most recently Greg Douglas performed a wonderful templated C++ version implemented in a single header file to produce type-safe, RTrees of arbitrary dimension.

    Download R-Tree code C version
    Download R-Tree Templated C++ version

Callbacks in C++

The C++ language has syntax to support almost every construct you would wish for, so when I needed to use a simple Java-style callback pattern, I was astounded when I found out just how difficult that is in C++! In the end I was able to do it but only by combining two really big guns: the Boost "signals and slots" library plus macros with arguments. Including the following pure-header file implementation, you can easily use the implemented macros in your observable classes to implement all the needed mechanisms for each listener event that you want to support

    View the code

Skiplists

Skiplists are fast associative collections invented by William Pugh. Key/Value pairs are added to skiplist containers and can then values looked up extremely quickly by key. The implementation is based on a fairly generic one originally in "C" by Bruno Grossniklaus which I converted into a C++ class library.

    Download SkipList code

Quaternions

Implementation of a simple C++ quaternion class called "Squat". Popularized by a seminal paper by Ken Shoemake, a quaternion represents a rotation about an axis.  Squats can be concatenated together via the * and *= operators and converted back and forth between transformation matrices. Implementation also includes a wonderful 3D vector macro library by Don Hatch.

    Download Squat code

Polygon-Cube Intersection Testing

"C" implementation of an extremely fast and robust polygon-cube intersection test by Don Hatch and myself as published in Graphics Gems V. Very useful for collision detection and view frustum visibility checking.

    View the readme file
    Download PCube code



Back to the Superliminal home page.