Tag Archives: Java

Java’s JTabbedPane CAN run custom behaviour per tab hover.

I’ve been getting quite a bit of time lately to my own hobbies. I finally got around to implementing some user-friendliness with PersonalFinancier, involving a status-bar at the bottom of the application for supplying a little user guidance.

Unfortunately, part of what I wanted to do was have a custom message per tab appear as I hovered the mouse over a tab. Like in the screenshot below.
Continue reading

Gradle and Java Dependency Library Management

Recently I learned that I couldn’t easily merge the encryption library I settled on into my main one without pain. As this is a sporadically visited hobby, I don’t have the free time to get to the bottom of it. As we’re dealing with a signed jar around security, it’s possible I’d be pushing s**t uphill anyway.

You might be aware by now that I like to solve the trusting of 3rd-party library problem by simply glueing those libraries into the final executable. If I can’t have that ideal, I want a model that’s as close as I can get to it.  I decided I’d get gradle to merge those dependency jars that are easy to merge, and ship the ones with issues as external dependencies.
Continue reading

5 things to know about AES Encryption in Java

Recent revelations around security on the Web have left me shaken, not stirred. If I can’t trust people in positions of power to respect the concept of ‘innocent until proven  guilty’, it strikes me that withdrawal of my trust would be a rather rational response.

To that end, I’ve been consumed this past week with figuring out how to password encrypt certain files I’m generating that I’d rather people spend effort on if they stumble across them.  I also freely admit that my inner Loki is mighty pleased by picturing the delightful dilemma others may face in trying to square off my ‘secrets most mundane’ against the inevitable sunken cost fallacies they’ll need to concoct to justify the discovery time.
Continue reading

PersonalFinancier gets an Aussie Inflation Calculator

I have a hobby programming project that has been mothballing until about a fortnight ago, when I decided to risk trying pushing some new functionality out.
I call it PersonalFinancier, and it’s hosted on GitHub under an open-source licence.

Since finishing the budgeting functionality, the itch to push the functionality out pretty-much stopped. I’d answered my cash-flow concerns, and was once again in that pleasing place of being certain that it was alll ticking over quite happily without my needing to watch it closely.

PersonalFinancier's Budget Tab @ 10/05/2013`

PersonalFinancier’s Budget Tab @ 10/05/2013

Lately, I’ve been itching to answer a new financial question that ultimately needs me to compare monetary values across over a decade of elapsed time. Now… I could just have visited the ABS, and used their inflation calculator, but where’s the fun in that? I’d written something very similar way back in the early 2000s when I was first cutting my teeth on Java, and frankly, looking at that code now is pretty painful. I decided to nuke it from orbit, because let’s face it… it’s the only way to be sure!

Tonight, I pushed the last commit up to GitHub that implements my Inflation Calculator. Though the calculator looks similar to the original in terms of its user-interface, the guts of it was a complete rewrite.

This flash new calculator involves two separate inflation models. The base model captures and manages CPI figures published by the ABS (or if you care for some serious scenario planning, a completely fictitious set). The second model is devoted to the calculator itself, and acts as one of the MVC viewers to the base model, the other viewer being the table widget used to render the CPI figures.

PersonalFinancier's Inflation Tab @ 10/05/2013

PersonalFinancier’s Inflation Tab @ 10/05/2013

It also takes a “favour composition over inheritence” approach to constructing the GUI. Inheritance of GUI components is a weakness that I’ve been known to fall into in the past, so this build has been a deliberate attempt to construct a rich GUI experience without defaulting to a deep nested inheritance structure for my tweaked Swing widgets.

Right now, the CPI figures are stored as a JSON encoding of the data, making it dead easy marshall between POJO and serialised state via that sexy little open-source library Gson.

In fact… here’s a link to the CPI figures as a JSON encoding. Building a POJO to match I leave as exercise to the reader. No promises I’ll keep it up to date unless someone reminds me that I’ve let it get stale.

Next step… putting a pretty graph into that unused panel. Here’s to the kids keep up their disinterest in my nightly itch-scratching.

Strict MVC Checks in Java

Lately, I’ve been digging into my finances (kids, they’re as expensive as they are adorable). My budget was somehow borked, but a surface experiment with it delivered no joy.  I realised I had to go deeper.

To figure out why the budget said I was in the red, but the bank balance continued getting happily more black, I decided that I would redo the budget utility. The budget initially started out as an Excel spreadsheet, then got beefed up with some Excel/VBA, which at some stage I moved across to OpenOffice and its not quite-the-same macro language.    The decision to go with Java was nothing more that wanting to brush up on my rusty Java skills.

The utility goes under the working title “PersonalFinancier”, and can be found on GitHub. Here’s a picture of it currently doing its magic:

A screenshot of the PersonalFinancier

A screenshot of the PersonalFinancier

Now, there’s an amount of MVC going on in the utility itself. There’s a budget model, a bunch of controllers, and a small number of view components. The most important view components are the tables that watch most of the model state one way or another.

I decided at some stage that with the MVC, I wanted to be absolutely certain at runtime that I had my views and controllers explicitly state that they were views and controllers.  I also wanted the system to check that this was the case.

The solution I settled on involved a design-by-contract approach implementing the following:

  • Separate interface definitions for the view and control classes of any given model.
  • The model checking at subscription time that the subscriber implemented the relevant view interface
  • The model checking whenever state was being updated that the state-altering class implemented the controller interface
  • The checking mechanisms implemented as asserts, allowing me to switch the checking off on a release build, but have them actively enforcing their interface contracts in a development/test build.

Below, the solution in gory detail:

MVC View and Controller Contracts

I introduce two interface definitions per model. One for the model viewers, and one for model controllers. The wiew interface extends Java’s Observer interface, as I’m happy to use the Publish-Subscribe pattern support that comes straight out of the box.

/* public interfaces for controller and view components to implement for a model */
public interface StrictModelViewer extends Observer {};
public interface StrictModelComtroller;

Runtime Model Checking with Asserts

My model class extends the Observable class. The example code below shows a method that changes model state that should only be invoked by a controller, and the “addObserver()” method of Observer overrriden to check that the new observer implements the correct view interface.

Given that these check functions seem rather generally reusable, the assert calls delegate the checks to a class library of generic reflection utilities.

The state-changing controller check is handled by the call to ReflectionUtilities.callerImplements().

Checking that the observer implements the correct view interface is handled by the call ReflectionUtilities.classImplements().

public class StrictModel extends Observable {

  public void alterModelState() {
    assert ReflectionUtilities.callerImplements(


   public void addObserver(Observer observer) {
     assert (
     ) : "observer specified does not implement the interface StrictModelViewer";


We typically can’t determine the caller of a method without reflection. The trick in Java seems to be to create a new Throwable instance,
and walk its stack trace back up to the call wer’re interested in.

Here, it’s not the callerImplements() call we want to know the calling method of, but the caller of it’s caller (two up the stack). Once we have the method, we check to see whether it’s defining class matches the interface we’re interested in. It
does this rather neatly via the classImplements() method.

   * Checks to see if the method calling whatever method that
   * invokes <tt>callerImplements</tt> implements the
   * supplied interface.
   * @param theInterface
   * @return
  public static boolean callerImplements(Class<?> theInterface) {

    StackTraceElement[] elements = new Throwable().getStackTrace();

    String callerClassName = elements[2].getClassName();
    Class<?> callerClass = null;
    try {
      callerClass = Class.forName(callerClassName);
    } catch (Exception e) {
       return false;
    return classImplements(callerClass, theInterface);

The classImplements() method interrogates via reflection, which interfaces a class implements and checks to see if one of those interfaces matches
the one we want. A naive approach of simply checking which interfaces a class implements, however, fails when it is the super-class of the one  specified that implements our desired interface. The reflection call getInterfaces() will only return the interfaces of a class, not including any super-class interfaces.

A thorough solution needs to check all interfaces implemented on the current class and all its super-classes. The getInterfacesForClass() method call below uses a touch of recursion to walk a class tree to the lowest base class, collecting all interfaces found as it goes.

   * Checks to see if the supplied class implements the supplied interface.
   * @param theClass
   * @param theInterface
   * @return
   * Checks to see if the supplied class implements the supplied interface.
   * @param theClass
   * @param theInterface
   * @return
  public static boolean classImplements(Class<?> theClass, Class<?> theInterface) {
    ArrayList<Class<?>> interfaceArray = getInterfacesForClass(theClass);
    if (interfaceArray.contains(theInterface)) {
      return true;
    return false;

   * Recursively build and returns a list of all interfaces implemented by the
   * supplied class and all its superclasses.
   * @param theClass
   * @return
  private static ArrayList<Class<?>> getInterfacesForClass(Class<?> theClass) {

    if (theClass == null) {
      return null;

    Class<?>[] interfaceArray = theClass.getInterfaces();
    Class<?> theSuperclass = theClass.getSuperclass();

    ArrayList<Class<?>> totalInterfaces = new ArrayList<Class<?>>();
    for (Class<?> currInterface : interfaceArray) {
    ArrayList<Class<?>> superClassInterfaces = getInterfacesForClass(theSuperclass);
    if (superClassInterfaces != null) {

    return totalInterfaces;

Deactivating Checking on a Release Build

The above is a rather heavy-handed approach to ensuring that only viewers view a model, and only controllers control it. Once I’m convinced that I’ve wired it all up correctly, I’d like to not carry these extra CPU-cycles at runtime. That’s why I’m using Java’s assert functionality here and have rigged Eclipse to run debugging with asserts turned on.  Note that a small amount of tinkering is needed in Eclipse to get asserts working.

And that’s how I’ve implemented actually checking that my model’s viewers and controllers are actually viewers and controllers for the given model.

Happy hacking!

Tales of the TeenyTyper #4: A BufferedImage of a JTextPane

I’ve just gotten back to my goofery with the TeenyTyper.  I decided I wanted to log images of the editor content whenever my beloved munchkin girl hits the “clear” button, and when the application finally quits.  Turns out that getting an image of the editor’s content is easy, but you wouldn’t know it from the dead ends out there in the Interwebs that implement flawed approaches.  I’m sure someone’s done this how I describe below,  but via my web trawling it’s either buried deep or just not documented for a Web audience.

Before describing the simple answer, here’s two links leading to solutions that don’t work, along with a discussion on how each fails:

Fail #1: The Robot Approach

Here’s a link to an approach that uses Robot to capture the content of the JTextPane as an image.  Yes, Robot has a convenient createScreenCapture() method.  What happens if you’ve typed content into the editor that’s bigger than the bounds of the editor?  Sorry bub, this code can only ever captures what’s on screen.  Usability is thus too limited for my liking.

Fail #2: Selection Rectangle-mania

I coded this solution up.  It’s involved to say the least, and based on converting the cursor positions of the beginning and end points of selected text into coordinates that then gets turned into a rectangle we’ll take an image snapshot of. Once it got it working, I realised that it was limited in painful ways.  If the end cursor position is shorter in width than the widest point of selected text, the rectangle will truncate all valid text within the selection that’s beyond the end cursor point with extreme prejudice. It’s also buggy as-written, so I was thrown for a while sorting this all out (can’t quite remember what now.. I think it had something to do with a transpose() call doing crazy things).

The Win:

So.  Here it is.  All the code you need to scoop the entire content of a JTextPane out as a BufferedImage:

BufferedImage editorImage = new BufferedImage(

Graphics2D g = editorImage.createGraphics();


The JTextField already knows the width and height of the rectangle it needs to render without the scrollbars.  It’s exactly the rectangle of image that I want to capture. All I had to do was to paint the text pane’s content to a new Graphics2D object of the BufferedImage.  As-is, the painting is a little too literal, and will also draw in the caret.   I turn off caret visibility off briefly as I paint, and whallah!  I now have a BufferedImage that Is dead-easy to log to a PNG file  with something like:

try {
 } catch(IOException e) { 
   System.out.println("Image save error: " + e.getMessage());

I’m obsessing at the moment over how many ways this can be done (or not as the case may be).  If you’re aware of another approach, flawed or fine, leave me a comment and I’ll weave it into the story.

Live long and image capture your editor panes!

Tales of the TeenyTyper #3 – The ActionBinder

In building the TeenyTyper, I decided that I wanted  to avoid the usual window decorations (like a close button).  A special key combination of <CTRL-D> would be instead used to shut down the toy once we’d finished playing.

I’ve tried implementing  Swing’s KeyListener interface in the past, but I’ve experienced the occasional KeyListener event not firing when it should have.  Sure enough, my first attempts at using a KeyListener misbehaved as expected.  A quick trawl of StackOverflow, and I hit gold.   Seems that I’d be far better off using key bindings instead.

So, in essence, I’m binding a particular action to perform for a given Swing component every time the component catches a relevant keystroke event.  Below is the reusable library function I settled on to establish this relationship:

public static void bindKeyStrokeToAction(
                     JComponent component,
                     String keyStrokeLabel,
                     KeyStroke keyStroke,
                     AbstractAction actionToPerform) {

  InputMap inputMap = component.getInputMap(



I’m not a big fan of that keystroke label requirement in the mapping. I have no need for the string itself once the mapping has been established. The string really could be anything for all I care (at least for this application).  To hide this string detail, and make the interface even easier to use, I implemented a wrapper to auto-generate a unique string mapping via Java’s UUID functionality like so:

public static void bindKeyStrokeToAction(
                     JComponent component,
                     KeyStroke keyStroke,
                     AbstractAction actionToPerform) {


So, implementing an action that shuts the TeenyTyper down gracefully when <CTRL-D> is pressed on the editor pane is achieved with the following call:

            KeyEvent.CTRL_DOWN_MASK), // <CTRL-D>
        new AbstractAction() {
          private static final long serialVersionUID = 1L;

          public void actionPerformed(ActionEvent arg0) {

And that’s it. No more KeyListener event misfire blues for yours-truly.

Keybind your actions long and prosper.