Browse Tag

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.

The coolness of a 3D desktop

Well it’s happened I have been working full time for over a year now and I am just getting more and more slack at writing valuable stuff on my blog, he he he.

But something most wonderful has happened over the Christmas break the alsa bug report tracking the problem with my soundcard has heated up, and someone found that by poking a register my soundcard will work under Linux.

So I have been spending the last few weeks getting back into my OS of choice.

I have Compiz working which is the coolest innovation on the desktop in a long time. I actually started with the fork Beryl but that version has a problem with java swing that is only fixed for Compiz in a Beta update for Java6 but not Beryl. So I am now enjoying the spinning cube virtual desktop, wobbly windows and the like in all their glory.

I also received an old Dell Latitude 600m which I mentioned I could use as a server box at home. The idea was to use it to host a webserver for AME, if I ever get it finished, so that I could host my own ads and receive full donations as per the sourceforge terms of service. But since I have not managed to finish it yet, I have been finding uses for it as a home server.

Such as using it to host torrentflux, as well as a SAMBA server for home multimedia sharing and I think I will get rid of my embedded print server and use it as a print server for the house aswell no need to pay for multiple devices to be running all the time.

And our land development has been pushed back to a release some time in April so house is on hold for now. Should get this post out it has been way to long coming till next time.

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.

Summer School

Well today I started summer school, o yey, doing Professional Issues in Information Technology and as most people who read this would know the first lecture consists of watch i, robot and writing an essay on it. But lucky me with the accelerated course doesn’t get the week to write the essay I get just one day so before I go off and start to write the next masterpiece I thought it was time for a bit of procrastination.

I have finished work for the year since this summer school stuff will just be too much work to even think about working in the afternoons and on top of that we are moving Thursday week so the house is a mess and you know that moving is a stress in itself at any time in your life.

We also finally upgraded our digital camera the other day. We went out and got a Canon S2 IS, which doesn’t have any RAW format but that is my only gripe about the camera it takes images and video and stores it fast which is a nice change from my previous camera, my trusty Kodak DC215 which in it’s time was the first cheap camera with optical zoom. But it just doesn’t cut it today anyway here is pic of me sized down from the giant 5MP which is just a bit too much to put on a blog :P.

I am also now working on a piece of software for my wife, scratching an itch as always however it is hers not mine. It is a teachers journal program for keeping track of different aspects of students and teaching. I am hoping to have a working alpha for her when school goes back in the new year but we will see. Software Development always takes longer than expected. It is written in Java of course but this time round I am going to use SWT instead of Swing which is a bit of an adventure. I will keep you posted, maybe a few screenshots when I get something working and a link to the site once it is release, open source of course.

Till the sands of time do we meet again, “Keep on truckin’”

  • 1
  • 2