A little teaser
Here’s a simple demo of a library that i’ve been working on over the past few months. I’m going to talk more about it over the next few entries, but for now enjoy the teaser:
Here’s a simple demo of a library that i’ve been working on over the past few months. I’m going to talk more about it over the next few entries, but for now enjoy the teaser:
There’s a new article that has been published today on java.net titled Debugging Swing. It builds on the previous work by Scott Delap and Alex Potochkin to provide even more tools for tracing the EDT violations that can lead to visual artifacts, unresponsive or frozen UIs and infinite painting cycles.
If you’re interested in more articles on Swing, please post your suggestions in the comments. Specifically, i’m looking for the “everyday” problems that you’re facing in the regular business Swing applications. Note that an article scope is too small to talk about architecturing a Swing application, so try to keep it to a specific topic, such as auto-completion support on comboboxes or writing a custom component.
Thanks to Eamonn McManus for his help on JMX-related code and to Chris Adamson for the editing.
While the Wikipedia entry on duck typing is quite thorough, Dave Thomas has a much more succinct and simpler definition:
In Ruby, types are defined as the capabilities of objects.
And that is a very interesting definition. Unlike with strong statically-typed languages (such as Java), Ruby doesn’t care about the actual type of the object being passed to a method, as long as it has all the methods that are used in that specific context. Leaving the relative merits and shortcomings of this approach aside for another entry, is this something that can be used in Java? Or, more interestingly, is it something that is used in Java? The answer is quite simple – yes. And not in third-party code; in the JDK itself.
The first example will be the Serializable
interface. This is an odd duck (quack quack :). On one hand, it is a marker interface since it has no methods. On the other hand, classes that require special handling during the serialization / deserialization must define implement special methods with these exact signatures:
private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException;
private void writeObject(java.io.ObjectOutputStream stream) throws IOException;
private void readObjectNoData() throws ObjectStreamException;
At runtime, the ObjectStreamClass
uses reflection to query the actual object to see if it has these methods. If it does, they are used (once again, using reflection) instead of the default (field by field) behavior. The reason behind having the Serializable
interface empty and the method signatures “magic” is, quite frankly, not apparent (you’re welcome to shed more light in the comments). What would happen if these were defined publicly in Serializable
(and had empty implementation in a hypothetical SerializableAdapter)? It’s not that suddenly anybody would gain access to the internals of the specific object. Calling writeObject
directly is the same as creating an OutputObjectStream
and calling writeObject
on it. Not only that, even with the current “duck” implementation you can use reflection to query these methods, set them to accessible and call them. A minor annoyance in having all these methods in the Serializable
interface would be that you would have to implement all of them if you already extend some other class.
The second example is the UIManager.getUI
method. This is where it gets even more complicated than the serialization. To create a UI delegate for a specific component, the implementation first looks up the classname of the UI delegate in the table set up by the current look-and-feel. Then, it uses reflection to call the “magic” static createUI
method that must have a single JComponent
parameter. This method is then called to create an actual UI delegate. Interestingly enough, this elaborated lookup is not really necessary. The code can be made compile-type safe by using a simple factory that returns UI delegates based on the passed component; just as the look-and-feel fills the lookup table (UIDefaults
), it can use the same “switching” to create the UI delegates. The issue with handling third-party component suites such as SwingX or JIDE can be easily addressed by providing an API on the look and feel class that allows installing lookup extensions. This example is a little further from the “pure” duck typing in that it returns a ComponentUI
object. This is, of course, not strictly necessary since the relevant code can use reflection to call the methods declared and implemented in this class (which could be quite tiresome, but certainly doable).
There are a few other places throughout the JDK code that use reflection – notably for beans, JMX, a few XML parsers and even the <a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html">Class</a>
class itself (in the <a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getEnumConstants()">getEnumConstants</a>
) method. And so, the next time you hear somebody mentioning duck typing, know that this technique is not restricted to dynamically typed languages.
This forum posting on the SwingX forum has caught my eye:
Having recently switched my main development box to Linux, I have noticed that swingx Linux support is pretty sparse. […] I have had a little dig, and the main culprit seems to be the LookAndFeelsAddons class, more specifically the getSystemAddonClassName() method which only seems to recognize the OSX and Windows OSs – everything else will be defaulted to a ‘Windows Classic Look and Feel’ ! As a result of this, my JXTaskPanes have no visual shading in either the title panel or the main panel. The weird thing is that JXTitledPane actually looks OK (it uses the correct colours for the title bar gradient).
And here is what Richard Bair (the lead of SwingX project) had to say:
The answer may not be very simple either. Since GTK is skinnable, we have to decide how to go about writing UI delegates for these things. Some things like JXStatusBar may have an equivilent type of component in GTK (not sure) which means we’d want to hook into the GTKLookAndFeel somehow to get the right painting code from the OS. Not sure if there is public API in GTKLookAndFeel to do that. And worse for those components that are more custom, like JXMonthView. How do we know what colors to use? I guess it depends on whether GTKLookAndFeel gives us any hints. Adding support to LookAndFeelAddons for Linux/Solaris is the easy bit. Figuring out what to do about it is quite a bit more complicated.
And this brought me back to think about the whole native-vs-cross platform debate that surges every few months in different Swing forums and blogs (with some taking very extreme stance). In this entry, however, i want to compare the implementation costs of these two approaches (and please don’t start flamewars in the comments on which one is better from the user perspective – this entry is about the implementation and not about the visual result).
First announced more than two years ago, the implementation of two core Swing look-and-feels (Windows and GTK) has moved from emulation to using native APIs. As Chet says on his blog
In Java SE 6, the Swing native look & feel for both Windows and GTK was re-written to use the native platform rendering engine to draw Swing widgets. Instead of our old approach of using the native resources and doing our own rendering, we actually call the native rendering system to draw the widgets for us (on Windows, this is done through the UXTheme API). This means that we are finally able to achieve true native fidelity for these components because, by definition, our components are drawn in the same way that the native components are. Not only did this fix corner cases for our XP look & feel, we also made our native look & feel work successfully on Vista.
Hooray going forward? 100% native fidelity for Swing applications running under XP and Vista? 100% native fidelity for Swing applications running under the next Windows release without any change to JRE? Not really. The devil is, as always, in the little details. So, what are they?
Native APIs change. As Chet mentions, Vista draws some components in different ways, so the code for those is different for XP and Vista. Who knows what will be in the next Windows release? Of course, Microsoft is committed to support the old APIs, but it doesn’t mean that the visual results are the same.
Native animations work on native controls. Since Swing controls are lightweight, they are just a bunch of pixels as far as the OS is concerned. This means that Swing has to emulate the animations for the specific OS. In Windows LAF this is done in the AnimationController class that tries to mimic different transitions on various controls. It also makes some assumptions on the native implementation (it assumes that the animations are linear which may not hold in the next Windows releases).
Native painting works on native controls. As with the previous bullet, this means that Windows LAF implementation must map the control state (rollover, pressed, selected, armed, enabled) to the matching OS control state (the later is passed to the native API that computes the colors that match the state). Vista defines over 50 different control states. The next Windows release may define more.
Texts are painted by the Java rasterizer. Many have complained about the rendering quality of default Windows fonts (Tahoma on XP and Segoe UI on Vista), and Karsten Lentzsch even went as far as this:
As a result of this bug [6449753], I consider using the SWT in high-fidelity Swing design to catch up with ClearType (XP) and ClearType (Vista).
Note that this might get better or worse with replacing the existing font rasterizer with FreeType in JDK 7.0.
Native painting supports only native controls. This actually brings me to the forum posting that i quoted in the beginning. With a lot of development going into comprehensive component suites such as JIDE and SwingX, how would one paint controls that have no direct OS counterparts? While in some cases you can address this by “stitching” together background tiles, what would you do with more complex controls such as Office 2007 ribbon, especially if you want to support all OS themes in Windows and GTK?
Native painting is harder to debug. Once you cross the line between Java and native calls, the debugging becomes more complicated. Now you’re dealing with JNI, native methods, possible leaks of native resources etc. On the other hand, the painting implementation itself is done on the OS level, which in most cases would mean less color-level bugs that you need to worry about (as long as you send the right parameters to the native methods).
Native painting is only painting. Java still needs to emulate the “feel” part of the controls. Since all the event handling is done by Java, it needs to “recreate” the keyboard and mouse user interaction with the component (which is just a bunch of pixels as far as the OS is concerned). When the next OS version adds new behavior (feel), Swing needs to add it explicitly.
As you can see, there are quite a few reasons why there are still bugs in the JDK 6.0 implementation of Windows and GTK LAFs. You also might consider these if your requirement is to have “absolute native fidelity” for your Swing application (whatever that means and once again, please don’t start a flamewar that there is no such thing as a native application since Microsoft breaks their own guidelines all the time). Note that this doesn’t mean that you should ditch Swing and move to SWT (or to native code for that matter). It’s just all those implementation quirks lurking just beneath the surface that might rear their ugly head and bite you at a very inopportune time.