James Williams
LinkedInMastodonGithub

Using classic Swing components with SwingXBuilder

Tags: SwingX

Because they aren't core Java, the mileage really varies when it comes to how SwingX components will be drawn in different Look and Feels. For some components, like JXButton, I didn't find myself often using any of the SwingX capabilities anyway. Sometimes I really want just a JButton instead. Because the new Button Factory replaced the old one, I would have to use a combination of another SwingBuilder object and the widget node in a somewhat contrived manner:

def swing = new SwingBuilder()
def swingx = new SwingXBuilder()
def frame = swingx.frame(size:[300,300]...) {
    label(text:'Hi')
    widget(swing.button(text:'Click me'...))
}.show()

Add an actionPerformed closure and it makes for a very ugly and hacky line.

Enter the "classicSwing" attribute

The classicSwing attribute is new to SwingXBuilder and takes a boolean value. If it is set to true, SwingXBuilder attempts to create the node using a member instance of plain old SwingBuilder, otherwise it executes the createNode function using the updated factory map. The above Groovy code is now:

def swingx = new SwingXBuilder
def frame = swingx.frame(size:[300,300]...) {
    label(text:'Hi')
    swing.button(classicSwing:true, text:'Click me'...))
}.show()

Aaaah, much more clean and concise.