Browse Category

Java

Vertical text align of radio buttons in java

I have been doing some GUI java code in both swing and SWT recently and find text alignment a niggling annoyance of mine. Often you want to align components with the text line vertically of combo or check boxes.

Here is the code for determining the width in pixels for the two most popular GUI libraries in java. Both are cross platform/look-and-feel solutions.

Swing

JRadioButton radio = new JRadioButton();
int raddioButtonOffset =
    UIManager.getIcon("RadioButton.icon")
        .getIconWidth()
    + radio.getIconTextGap()
    + radio.getInsets().left;

SWT

// get the width of a space
GC gc = new GC(parent);
int spaceWidth = gc.getAdvanceWidth(' ');
gc.dispose();

// create radio widget to get widths
Button radioButton = new Button(parent, SWT.RADIO);
Point baseSize =
    radioButton.computeSize(SWT.DEFAULT, SWT.DEFAULT);
radioButton.setText(" ");
Point withSpaceSize =
    radioButton.computeSize(SWT.DEFAULT, SWT.DEFAULT);
radioButton.dispose();

int radioButtonOffset =
    withSpaceSize.x
    - ((withSpaceSize.x - baseSize.x) / 2)
    - spaceWidth;

Netbeans

I have become a bit obsessed with the java community lately more in a consuming fashion than a participatory fashion, reading Java Desktop and listening to the Java Posse and it just keeps coming up how much everyone loves Netbeans and that everyone should be using it for Java development.

Features such as Mattise look to be very good and a great reason to use the IDE. However as an Eclipse user there are just too many features that I miss to change IDE for now.

  1. Per project settings including templates and code style
  2. Macro for YEAR for code templates
  3. Incremental compiler.
    On a small project of only one file takes a good 3 seconds just to launch even if it is built. Like really do you need to build a jar always when executing projects? As good as running everything through ant sounds it is just too slow when compared to what you get for free with eclipse.
  4. Editor support.
    Supposibly the java editor is greatly improved for version 6, however in the test build I used M9 it is still slow, non intuitive and just painful give me eclipses Ctrl-1 quick fix any day.

Completion in the IDE space is good but for my everyday java development it is still impossible for me to switch.

gstreamer port to Java

It has long been discussed in the java community about the lack of a good multimedia framework for the platform. After reading Chris Adamson’s wrap up of his JavaONE BoF I felt here is a cause I could really get behind.

I starting thinking yes wouldn’t it be great if gstreamer was ported to java. I started doing some research and grabbed a copy of the gstreamer cvs. But just as I was getting my hopes up I read that sun was going to do something about multimedia. But by the time I got to the end of the blog entry I realized that it is a smaller project of giving a common java wrapper for the platform services ie Qucktime on OSX, DirectShow on Windows and I guess gstreamer on Linux.

As the days went on and the comments on Chris Adamson’s blog kept commoning many people believe that a full stack is needed but no one is willing as far as I can tell willing to have a go at it. One even goes as far as to say that it is too hard because gstreamer usually just wraps other binaries such as ffmpeg and would just be too hard.

There is also the Cortado sub project of flumotion which is a very simple applet for viewing ogg theora videos. At it’s core there is a partial port of gstreamer that is undocumented and is very C-style coding.

So for fun I want to start trying a full port, so I have read the gstreamer application development manual and the plugin writers guide and now feel I have a fairly good understanding of what is under the hood and how much work this is going to be. I think alot more than I even realize right now.

A few design features I am thinking of going with now are:

  • Full java stack as far as possible only pure hardware plugins such as video4linux etc would call native code.
  • Rewrite all previous java implementations ie, jorbis.
  • Elements as POJO’s and use introspection for properties rather than a map.
  • Java SE 6 only.
  • Heavy use of java.util.concurrent.
  • Core released as GPL plus classpath exception and plugins most likely GPL.

Now I know it will be a lot of work and knowing me it will probably never be released but if you think this is a good idea and want to put you 2c’s in then please leave a comment.


Update: 16 Jan 2009

Well with the release of JavaFX and the fact that I never have any time to code outside of work I guess this idea will never actually come to fruition.

Asserting SwingWorker

I have had a chance to play around with some java code recently for a change of pace and I was excited to use the new SwingWorker class in JSE6. However I also am in the habit of programming with asserts which I found out to be a problem if one triggers while running in a SwingWorker thread.

If you look at the base class of SwingWorker, FurtureTask, in the inner class Sync, which is where the actual task is run there is this method:

boolean innerRunAndReset() {
    if (!compareAndSetState(0, RUNNING))
        return false;
    try {
        runner = Thread.currentThread();
        if (getState() == RUNNING)
            callable.call(); // don't set result
        runner = null;
        return compareAndSetState(RUNNING, 0);
    } catch (Throwable ex) {
        innerSetException(ex);
        return false;
    }
}

The observant reader will notice that this code will catch all Throwables, which is the base class of Exception and Error, and an assert in java will throw a AssertError so your code will bomb out silently without notification if any Throwable is thrown.

try {
    // do threadded work here
} catch (AssertionError e) {
    logger
        .log(Level.WARNING,
        "Assertion while processing: {0}\n{1}",
        new Object[] { e.getMessage(),
        e.getStackTrace()[0] });
} catch (Exception e) {
    logger.log(Level.SEVERE,
        "Exception throw during processing {0}\n{1}",
        new Object[] { e.getClass().getName(),
        e.getMessage() });
    throw e;
} catch (Error e) {
    logger.log(Level.SEVERE,
        "Error throw during processing {0}\n{1}",
        new Object[] { e.getClass().getName(),
        e.getMessage() });
    throw e;
}

I use the a statically defined Logger, logger, to print output from the Exceptions and Errors.

This allows the thread to throw asserts but keep going and if it does bomb out on any other Error or Exception you get notified in your log making debugging a SwingWorker a bit easier.

Open Java and Windows Options

Well it’s officially been announced that Java J2SE, J2ME, J2EE will all be released by sun as reference implementations under the Gnu GPL + classpath exception. Which I’m sure will bring a new era of Java, especially to Linux since Java will be able to be shipped with distributions without concern just like Mono is today.

I really hope this means the MVM will get done faster it would be a great thing for the platform.

On a unrelated note one of my pet peeves about Windows is the way that Explorer.exe works. The problem is that it is the window manager as well as the file browser. What I usually find is that the file manager will lock up the window manager which is most annoying. However there is an option to make them work in separate processes which users more memory but for the stability of the system it’s well worth it.
Edit In Seperate Process

Code Cutting

Well this page always seems to get a bit neglected when nothing much happens……

Something interesting that I have come across is the w3c DOM in java and how there isn’t a definitive guide to how to output it to pretty print, ie human readable, there were a few examples with xerces-j but I thought that wouldn’t work but I tried it for good measure and it works. Even with the option that appears to be for xerces. Heres the code.

TransformerFactory tFactory = TransformerFactory.newInstance();
try {
    Transformer transformer = tFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{xml.apache.org/xslt}indent-amount", "4");

    DOMSource source = new DOMSource(document);
    transformer.transform(source, new StreamResult(f));
} catch (TransformerConfigurationException e) {
    e.printStackTrace();
} catch (TransformerException e) {
    e.printStackTrace();
}

Have fun and I found a great plugin for doing the code colouring, iG:Syntax Highligher.

Interesting Java Proposal

In the java community there has been a long and heated debate about adding delegates to the language. There is a white paper on Suns website explaining there position on the debate. Which is in response to Microsoft’s implementation of them in J++ which in tern could be deemed as the turning point for Microsoft to then create the entire .NET architecture. Although it doesn’t have a date on it using the way back machine we can see that the paper has been around at least since the beginning of 1999.

I hadn’t read the paper until just last week and I agree with what it’s saying functors/delegates are a quite strange structure in c/c++/.NET and can be difficult to explain. On a side not I have also read that Java is a much more strongly OO architecture than .NET, which is more an easy wrapper over windows as always (grr I can’t stand MFC) anyway… I was looking at some new features for c# 3.0 and in particular extension methods which I am of the opinion are really syntactic sugar for the lazy VB programmers out there, ducks for cover.

But in my search I also found a new paper that is proposed for Java written by three prominent figures including James Gosling, the farther of Java, Closures for Java, there is a pdf but this is a verbatim copy on Neal Gafter’s blog.

Neal has 4 other posts about them and I recommend reading them all if your head can get around them, it took me 2 goes at it. I can see how these constructs could be very useful in getting rid of boiler plate code from a lot of Java programming, which is always a good thing, but I can also see it becoming a problem as well when used too much. Since it is a way of almost changing the language itself you could quickly start having the same headaches you get for heavily preprocessed c/c++ code.

I am still not sure as to whether they would be a good thing for the language if introduced it will be something that will probably not make it into begging programming courses. One of the things I have always liked about Java is that once you understand the OO principles of the language which can be picked up in a short amount of time virtually all api’s and constructs can be created by the programmer. If not very well designed used but use none the less.

I’ll keep tracking Neal’s blog for more insights into uses before I am really sure but it is none the less a very radical and interesting proposal none the less.

Big News

Well once again me like some of my friends find it hard to actually get to the content page and add new stuff to their blogs but I think the news of the last 2 weeks really deserves a blog post.

Well probably the biggest news is from this week, Merinda and I have bought a block of land! And get this it’s in Mernda, that will make for interesting conversations and lots of spelling names over the phone. And it only took us a week to go from looking at existing properties to buying land and looking at houses to build!

With stamp duty here in Victoria being so high it doesn’t really make much sense to buy a fairly expensive property that will be over 20 years old.

The other big news is that I received a employee recognition award which is always quite strange. It was for integrating one of Microsoft’s better technologies into our product, the ability to write mini-dumps in the event of crash. Which then allows us to see the stack and trace the line of code that the crash occurs on.

Finally I wish to say that mustang (or JDK6 as it is now known) ROCKS it makes programs such as jbidwatcher seem so much more polished. With true double buffering the windows no longer goes gray when repainting, and the new register allocator that I talked about a while ago makes every java application fly. It’s still in beta but when it releases for real it will be a great step forward and with the open sourcing of the platform to be complete by ruffly the end of 2007 I’m looking forward to more java technology into the future.

MMMM Mustang

I hate to just blog about someone else’s blog but hey improvements in Java like this don’t come around everyday.

In the latest build of Java 6.0, Mustang, they have implemented a better register allocator and have managed to speed up the Hotspot Client by 58%. Now that is amazing and with other improvements like lock coarsening and escape analysis this platform is just going to fly. I can’t wait.

Study

You know what one of the hardest things to do after a year off (I was on IBL for a year at VSL) is STUDY.

I was trying all of last week, I got a little bit done but really not enough. After last year when I could come home and forget about work to this year being back on 24/7 with everything really sucks. So what did I do I started coding… Probably not the best idea but it has been fun.

I’m working on a program I call “TimeTracker” which is really a task timer for work so that at the end of the week I know where my 7.5 hours a day go at work. It is mainly based on TimeTool for Windows. It’s written in Java of course and is a lot of fun to get back into the coding side so here is a pre-alpha screenshot of TimeTracker.

Pre-Alpa screenshot of TimeTracker

  • 1
  • 2