October 2004 Archives

Marc Hedlund

AddThis Social Bookmark Button

(For an overview of the G$D/Groovy series, see <http://www.oreillynet.com/pub/wlg/5789>.)

Radio buttons and SwingBuilder

This one is short and sweet. To make radio buttons in Swing, you instantiate a set of JRadioButtons and add them to a ButtonGroup. Only one button in a ButtonGroup will be allowed to be selected at a time.

You might think SwingBuilder would provide a buttonGroup() method that would allow you to contain radio buttons, but you’d be wrong:


import groovy.swing.SwingBuilder;
import java.awt.FlowLayout;

swing = new SwingBuilder();
gui = swing.frame(size:[250,100]) {
    panel(layout:new FlowLayout()) {
        // WARNING: This code won't work!
        buttonGroup() {
            radioButton(text:"One");
            radioButton(text:"Two");
            radioButton(text:"Three");
        } 
    }
}

gui.show();

There is a buttonGroup() method in SwingBuilder, but you can’t use it as a container. Instead, you have to create the ButtonGroup (using SwingBuilder’s buttonGroup() method) and hold it in a variable, and add it to the radio buttons as a property:


import groovy.swing.SwingBuilder;
import java.awt.FlowLayout;

swing = new SwingBuilder();
gui = swing.frame(size:[250,100]) {
    panel(layout:new FlowLayout()) {
        // This will work:
        myGroup = buttonGroup();
        radioButton(text:"One", buttonGroup:myGroup);
        radioButton(text:"Two", buttonGroup:myGroup, selected:true);
        radioButton(text:"Three", buttonGroup:myGroup);
    }
}

gui.show();

Here’s the result:

image

Marc Hedlund

AddThis Social Bookmark Button

In an earlier post this week, I railed against Sprint for disabling the use of Bluetooth on the new Treo 650 for laptop Internet access. Jeff Shafer from Sprint Business Solutions Public Relations contacted me and said the following:

It is important to note that the characterization [in your post] is inaccurate.

Due to some development deadlines, the phone has been launched as described, without the DUN [dial-up networking] capability.  However, as part of a scheduled maintenance release of software (timing pending some testing), the DUN capabilities will be supported.  We also support the functionality in the just released PPC-6601 (Pocket PC device).   In no way is Sprint suppressing the functionality as you describe or with the motivations you assert.

I’m glad to hear that Sprint will be supporting this functionality and is not trying to double-dip on mobile business users. I also asked whether the commentator on my previous post was right about the terms of service being a concern, and Jeff responded, “my understanding is that no, we do not have a restriction on these devices from a pricing/plan standpoint. This sort of use only represents a pretty small fraction of Sprint Vision customers, so we see it as one of those areas where if this is how customers choose to connect, we don’t stand in the way.”

Russell Miles

AddThis Social Bookmark Button

Related link: http://www.theserverside.com/news/thread.tss?thread_id=29619

If you haven’t checked out JBoss AOP up until now, now is the time to have a play with it! With the release of JBoss AOP 1.0.0 you get a great selection of features that are worth checking out.

But the best thing by far is .. the Eclipse plug-in support. Now JBoss AOP has one of the nicest IDE integrations that makes it as easy to develop in JBoss AOP as it is in AspectJ AOP. But don’t take my word for it; check out the cool video

Been using or even working on developing JBoss AOP? What’s your favorite features and does this release help the overall acceptance of AOP?

Marc Hedlund

AddThis Social Bookmark Button

(For an overview of the G$D/Groovy series, see <http://www.oreillynet.com/pub/wlg/5789>.)

Updating a running SwingBuilder UI and the secret widget() method

Once you have a SwingBuilder UI running, how does it ever change? Does it just sit there? Can it be changed programmatically? Good questions. SwingBuilder makes it easy to create Swing interfaces very quickly, but in the process you lose access to the component references you’d normally use to update your running UI.

Groovy adds two main ways to update a Swing UI (above the normal Java methods, which are of course still available to you if you don’t use SwingBuilder): action closures and widget references. We’ll talk about widget references here, and action closures in another post.

Take a look at this code from the basic SwingBuilder lesson:

import groovy.swing.SwingBuilder;
import java.awt.FlowLayout;

swing = new SwingBuilder();
gui = swing.frame(title:'Test 2', size:[400,200]) {
    panel(layout:new FlowLayout()) {
        panel(layout:new FlowLayout()) {
            for (name in ["Tom", "Dick", "Harry", "Bill"]) {
                checkBox(text:name);
            }
        }

        panel(layout:new FlowLayout()) {
            comboBox(items:["Red", "Green", "Blue", "Orange"],
                     selectedIndex:2);
        }
    }
}

gui.show();

Let’s say you wanted to add an item to the JComboBox sometime after the gui.show() call. How would you do that? Since SwingBuilder created the JComboBox for you, you don’t have a reference to it, and can’t call its addItem() method.

SwingBuilder has a secret method called widget() to help in this situation. I call it a “secret” method because it isn’t documented anywhere I could find — since it was added as a patch to fix two Groovy bugs (GROOVY-333 and GROOVY-501), only the bugnotes for those bugs provide any guidance. The purpose of the widget() method is to allow you to add a component to SwingBuilder that was created outside of the current SwingBuilder call. One reason to do this would be to add a custom component to a UI, one that SwingBuilder doesn’t support itself. In this case, though, the widget() method will let us keep a reference to the JComboBox, so we can add an item to it later. Here’s the updated code:

import groovy.swing.SwingBuilder;
import java.awt.FlowLayout;

swing = new SwingBuilder();

// first, create the combo box
comboBox = swing.comboBox(items:["Red", "Green", "Blue", "Orange"],
                     selectedIndex:2);

// second, create the rest of the gui
gui = swing.frame(title:'Test 2', size:[400,200]) {
    panel(layout:new FlowLayout()) {
        panel(layout:new FlowLayout()) {
            for (name in ["Tom", "Dick", "Harry", "Bill"]) {
                checkBox(text:name);
            }
        }

        panel(layout:new FlowLayout()) {
            // add in the combo box we made earlier
            widget(comboBox);
        }
    }
}

gui.show();

// ... more activity here ...

// finally, update the combo box
comboBox.addItem("Yellow");

As you can see, we use SwingBuilder to make two components — first the comboBox and then the main frame. Inside the frame call, we use the widget() method to insert the combo box where it belongs. Later on, we can call any method on the combo box we need by using the reference we kept earlier. Here’s the new UI, showing the added list item:

image

This is the approach that works, but there are plenty of approaches that don’t work! Assigning to a variable inside the SwingBuilder block? Nope. Putting a bare reference to an earlier-created component inside a SwingBuilder call? Nope. Using a closure to generate the component? Nope. You can beat your head against this problem for a long time (trust me!). Fortunately, the widget() call allows you to keep references to components or insert existing components into a SwingBuilder construct.

Marc Hedlund

AddThis Social Bookmark Button

Related link: http://www.electoral-vote.com/

There’s an excellent poll tracking site, Electoral Vote Predictor 2004, to which friends of widely varying political beliefs have referred me. It is great to see a site like this aggregating and analyzing information from all the pollsters. Since many media outlets sponsor their own polls, they often don’t take this approach. Good job, Internet!

As a Kerry supporter, I noticed two interesting things in the poll results:

  1. Many of my friends who support Bush say that the key issue for them is terrorism, and which candidate can best address it as a threat to the nation. It’s interesting to me that the three locations attacked on 9/11 (New York, Washington, D.C., and Pennsylvania) are all supporting Kerry. D.C., which has had an incredible onslaught of horrific, terrorist or terrifying events over the past four years (the Pentagon attack, anthrax and contamination of Senate offices, the sniper shootings), is far and away the strongest region supporting Kerry, with 78% in his favor. The people who have been most directly threatened by terrorism are voting for John Kerry.
  2. As many others have noted, it’s astonishing how closely this year’s poll results mirror those from the 2000 election. See, for instance, this CNN article from October of 2000. George W. Bush has, I imagine we all would agree, been one of the most forceful presidents in recent years, pushing his agenda and advancing the causes in which he believes. Certainly that resoluteness did not come through during the 2000 campaign — if anything, Bush seemed uninformed about international affairs, not driven by them. While I personally disagree with his goals, it is notable how aggressively he and his administration have pursued them. Given that, I find it astonishing that after four years, the net gain of support for Bush is 0. Wouldn’t you think that a leader who sets clear goals and persuades or coerces opponents to support them would gain at least the respect of people who appreciate that character of leadership?

    Consider the parallel of San Francisco Mayor Gavin Newsom. His election over Green Party candidate Matt Gonzalez was nearly as narrow as Bush’s over Gore. Yet by pursuing marriage rights for gay Americans, Newsom has won over a huge number of former Gonzalez supporters: his approval rating went from 62% at the election to 85% this summer. Why hasn’t the same happened for Bush? Bush’s approval rating went up after 9/11, but has spiked much more on external events than on the “forceful” actions he has chosen to take.

Of course polls are a mirror as much as a projection. I see in them what I hope for next Tuesday, that John Kerry will be elected. You might well see something else. I’m glad, though, to have a resource to help see through the typical news headlines.

Marc Hedlund

AddThis Social Bookmark Button

Related link: http://www.treocentral.com/content/Stories/474-2.htm

UPDATE: Sprint responded to this post; see the followup post for information about their response.

The new Treo 650 is out today — and as a long-time fan of the Treo, I’ve been looking forward to it. I’ve asked in the past for “one with everything” — a phone with all the features I could want in one device, without compromises. It looks like PalmOne delivered, with a 320×320 screen, removable battery, upgraded OS, a better camera, and Bluetooth.

Oops — not quite! TreoCentral is reporting that the Sprint version of the Treo 650 doesn’t allow you to use Bluetooth for dial-up networking through your computer. Apparently other carriers will, but not Sprint.

You see, Sprint sells connection cards, which are PCCards that allow you to dial up your laptop over their cell network. Apparently they were really unhappy when PDANet, an application for the Treo that lets you use the phone through a USB cable as a connection card, came out. I’m sure that’s what’s caused this “lock-out” to be added now.

As a business traveller, PDANet was a godsend (until I switched to a Mac laptop). I used my laptop online in airport terminals, hotel rooms, taxi cabs (!), and traffic jams. PDANet made my Treo completely invaluable to me, and made me a very happy customer, ready to upgrade to the 650 as soon as it appeared.

No longer. I switched to Sprint with the Treo 300 appeared, and now I’m switching away. If they think they can get me to buy another $250 product with another phone number and monthly service charge just because they switched off a built-in feature of my phone to force me into it, they are out of their minds. Their competitors offer a feature that they have decided to disable, so I’ll just pay them some more money so I can carry around another piece of electronics? They must take me for a complete idiot.

I’d recommend that if you have a Treo or are thinking of buying one, you switch networks away from Sprint. They don’t want the Treo to be useful to you.

Marc Hedlund

AddThis Social Bookmark Button

(For an overview of the G$D/Groovy series, see <http://www.oreillynet.com/pub/wlg/5789>.)

Basic SwingBuilder

Groovy contains an excellent set of features called GroovyMarkup. The basic idea of GroovyMarkup is to make it easy to create nested hierarchies of objects, such as an XML document, where tags contain other tags that contain more tags. GroovyMarkup works incredibly well for making Swing applications, which are composed of hierarchies of components such as windows and buttons. The GroovyMarkup tool for Swing is called SwingBuilder.

To use SwingBuilder, you’ll need to be familiar with the Swing components (not how to use them, but what they’re called and what they’re for). A simple overview, with helpful pictures of each component, is available at <http://java.sun.com/docs/books/tutorial/uiswing/components/components.html>.

SwingBuilder has a built-in method for each type of Swing component. When you call one of these methods, the corresponding Swing component is created. Your first method call creates the container (like the main window), and other components are created in the block that follows. Here’s a simple SwingBuilder example to get started:

import groovy.swing.SwingBuilder;

swing = new SwingBuilder();
gui = swing.frame(title:'Test Window', size:[200,100]) {
  label(text:"This is a test");
}

gui.show();

That’s all you need to make a basic window (that code is a complete script — no additional imports or calls are necessary!). Here’s what the result looks like:

image

The way to use SwingBuilder is to first create a root element — probably a frame (as in the example above), a window, or an applet. After each element call, you can open a block with a curly brace, and add any nested elements you want. (Inside the block, you can call the methods “bare” — that is, without calling them on the swing object, but just by themselves.) You can also use any other Groovy code — loops, if statements, other objects — mixed in with your SwingBuilder calls.

There’s a simple trick to making the Swing component method names — take the Java name for any Swing component, such as “JLabel”, remove the “J” and lowercase the first letter (leaving you with “label” in this case). Any Swing component can be made with SwingBuilder using this naming pattern — the “J-less” name is a method name available for you to use.

With the arguments to each component method call, you can set any properties for that component, which allow you to affect the component’s appearance and behavior. We do this with the title and size in the frame call, and the text of the label call, above. (If you are familiar with JavaBeans, these are Bean properties. If you are not familiar with JavaBeans, just look at the documentation for the Swing component you’re using, and look for methods starting with get and set — those are properties. In Java, you would call the setText() method, but with SwingBuilder, you just set the text property as an argument.) Add as many property settings to each component as you want.

Here’s a slightly longer example:

import groovy.swing.SwingBuilder;
import java.awt.FlowLayout;

swing = new SwingBuilder();
gui = swing.frame(title:'Test 2', size:[400,200]) {
    panel(layout:new FlowLayout()) {
        panel(layout:new FlowLayout()) {
            for (name in ["Tom", "Dick", "Harry", "Bill"]) {
                checkBox(text:name);
            }
        }

        panel(layout:new FlowLayout()) {
            comboBox(items:["Red", "Green", "Blue", "Orange"],
                     selectedIndex:2);
        }
    }
}

gui.show();

And here’s the result:

image

One thing to notice in this second example is that you can often set the model for a MVC component by using a Groovy list or map. Here, we set up the list of options for the JComboBox (better known as a pop-up list) by setting the items parameter with a Groovy list as the value. Much easier than the Java way!

A more complex SwingBuilder application is available in my Bloglines API Client article. That application uses a few other SwingBuilder tricks, like action closures and the widget() call, which will be covered in future posts. You’ll see that a huge amount of functionality can be enabled with very little effort — writing that same application in Java might easily have taken 50 times the lines of code.

Marc Hedlund

AddThis Social Bookmark Button

Here’s an index of the G$D/Groovy posts, which I’ll update as I add to the series, for handy reference:

Getting Started
Collections
Swing
Closures
Documentation
Russell Miles

AddThis Social Bookmark Button

Related link: http://aspectbench.org

Up until today AspectJ and the ajc compiler was the only real option for heavyweight aspect-oriented development. What was not so well publicized was that the clever bods at Oxford Universities Computing Laboratory were busy working on a new implementation of the compiler in order to push the bounds of what was currently implemented by the equally smart bods at IBM.

abc is the fruit of these labours but rather than be a unhealthy splintering of the AspectJ community, the release of 1.0.0 of The AspectBench Compiler (ABC) signals a new age of innovation for AspectJ. You see, the guys in Oxford have been working together with the IBM people to provide a compiler where new and and innovative technologies can be tried and tested before incorporation into the full AspectJ Development Environment adding a level of integrity and legitimacy rarely experienced by such a new approach.

This is not to say that abc is in any way a mere alpha test-bed. In fact, the abc compilers development has led to an excellent amount of feedback into the ajc in order to improve reliability and quality all round. But abc does add some facilities that promote innovation above and beyond the more traditional compiler approaches available in ajc:

  • An extensible frontend based
    on Polyglot
  • An extensible backend based
    on Soot
  • An ideal platform for experiments
    with new features and optimisations

So there you go. My advice to anyone using AspectJ is to give abc a try. Not necessarily to replace ajc and your regular AspectJ development environment, rather to giver yourself a platform to explore new ideas that could be incorporated into future implementations. With abc, this community finally has a place to actually try new things out and to have the opportunity to have those ideas promoted into real contributions to the evolution of AspectJ - if only other languages had the same opportunity.

What do you think of ABC? Do you know of other languages that would benefit from this from of true open experimentation in their development?

William Grosso

AddThis Social Bookmark Button

Related link: http://www.sdforum.org/SDForum/Templates/CalendarEvent.aspx?CID=1461

As readers of this weblog know, I occasionally mention SDForum and the Emerging Tech SIG (which, along with Janice Carter and Tom Hill, I help run).

This month, we’re holding a panel discussion on metadata and music.

The music industry has changed dramatically in the past 5 years (Napster is, at this point, only five years old). But, until this point, most of the change has been in the distribution mechanism and the players (internet-based to an MP3 player replacing going to the store to buy a CD).

Increasingly, however, what people are downloading, and how they found out about it, is changing as well. As
DJ Dangermouse shows, a hit album no longer requires airplay.

What’s next? What happens when you add more metadata to the mix? Come on September 12 and find out.

Please add references to musical metadata to this article.

Marc Hedlund

AddThis Social Bookmark Button

Related link: http://rtmark.com/funds.html

RTMark’s Mutual Fund project is amazing. Boing Boing linked to one of the projects yesterday, and their update led me to look through the Media Fund projects. It’s an incredible source of ideas. The Mutual Funds allow you to support projects in a market structure — what a fantastic idea. Check it out and invest!

AddThis Social Bookmark Button

So I want to rant a bit about J2EE and discuss how J2EE is similar to VisualBasic. J2EE is a framework while VisualBasic is a programming language. However, J2EE affords the Java developer an environment which allows him or her to not think about things like threading, database access, etc. and focus on the application development task at hand. This on the surface may seem like a good thing. It allows those developers who are less skilled or educated to build enterprise and/or business applications quite quickly, or at least that’s the promise. VisualBasic promised a similar thing. You could take people with little or no programming experience and let them point-and-click their way to application-development bliss. Of course you still need to know the syntax of the language, how to debug it, how to think logically, etc., but the learning curve of Visual Basic is a bit easier than that of say C or C++.

I work with an individual who recently made the statement that “everything in Swing is thread safe.” This is not correct. This individual, who has supposedly been working the software field for 10+ years, apparently doesn’t know the first thing about threading in Java, even though he claims to be a Java and J2EE guru.

This disturbed me to say the least. It is apparent that the proliferation of easy-to-use languages and check-your-brain-at-the-door frameworks are doing a disservice not only to individuals who use them, but the companies who employ these ignorant people. Of course, there are many people out there who are clueful and make use of J2EE and such, and these people probably end up learning how poorly suited J2EE is for doing any sort of high performace application and ditch it altogether. See Better, Faster, Lighter Java for a discussion on this. I can count at least three real-world, i.e. commercially driven, software projects I know of which started out as J2EE projects and eventually were killed due to performace issues, or switched gears and became either J2SE projects or had to be implemented in another language.

But I often wonder how many people who claim to be J2EE experts would know the difference between a nibble and a byte? Or how threading impacts performance on boxes with multiple CPUs. Does this mean that only computer science graduates should write software? No. But I think the cursory introduction that many non-CS types get to programming, software engineering, operating system design, hardware design, and algorithm analysis can make for poor practitioners. It is entirely possible to get this educational background without having a computer science degree. There are many well-written books on these topics. In fact I work with individuals who have non-CS degrees and have mastered most, if not all of these skills.

So, I am going to coin the following phrase, quip or whatever:

“J2EE: the VisualBasic of the Java world”