Implement a Groovy SwingBuilder script that creates a reactive UI where a button click…
- User
Implement a Groovy
SwingBuilderscript that creates a reactive UI where a button click updates a label using a bound property model. Assistant
Implement a Groovy SwingBuilder script that creates a reactive UI where a button click updates a label using a bound property model.
The user wants a Groovy script that uses SwingBuilder to create a UI.
The UI should be "reactive" (in the context of Swing/Groovy, this usually means data binding).
Specifically:
Let's break down the requirements:
SwingBuilder.JButton and a JLabel.Step 1: The Model
I need a Groovy class that supports property change notification. In standard Java Swing/Groovy, this involves java.beans.PropertyChangeSupport.
Groovy has a handy annotation: @Bindable.
If I annotate a property with @Bindable, Groovy automatically generates the boilerplate code for PropertyChangeSupport.
Let's define a simple model class:
import groovy.beans.Bindable
class MyModel {
@Bindable String message = "Initial Text"
}
Step 2: The View (SwingBuilder)
I need to instantiate SwingBuilder.
I need to build a frame.
Inside the frame, I need the label and the button.
The Label needs to bind its text to the model's property.
Syntax in SwingBuilder: text: bind(source: model, sourceProperty: 'message') or simply text: bind { model.message }.
The Button needs an action. The action should update the model.
Step 3: Putting it together (Mental Draft)
import groovy.beans.Bindable
import javax.swing.*
import java.awt.*
// 1. Define the Model
class ViewModel {
@Bindable String labelText
ViewModel() {
labelText = "Hello World"
}
}
// 2. The Script
def model = new ViewModel()
def builder = new SwingBuilder()
builder.edt { // Use EDT for thread safety
frame(title: "Reive UI Demo", size: [300, 200], defaultCloseOperation: WindowConstants.EXIT_ON_CLOSE) {
borderLayout()
// Label bound to model
label(text: bind { model.labelText }, constraints: BorderLayout.CENTER)
// Button to change model
button(text: "Click Me", constraints: BorderLayout.SOUTH, actionPerformed: {
model.labelText = "Updated at ${new Date().format('HH:mm:ss')}"
})
}.visible = true
}
Refining the "Reactive" aspect:
The prompt asks for "reactive UI where a button click updates a label using a bound property model".
The bind method in SwingBuilder is the key here. It creates a PropertyChangeListener under the hood.
Additional considerations:
SwingBuilder has an edt method. It's good practice to wrap the construction in it.@Bindable is usually available via the grape system or standard library depending on the Groovy version, but usually requires groovy.beans.Bindable).Let's write the code structure:
groovy.beans.Bindable, groovy.swing.SwingBuilder, javax.swing.*, java.awt.*.class CounterModel {
@Bindable int count = 0
}
Wait, the prompt implies text update. Let's stick to a String property.
class MessageModel {
@Bindable String content = "Waiting for click..."
}
SwingBuilder.frame.label with bind.button with action.Drafting the specific example: Let's make it a simple counter or a timestamp updater to prove it works repeatedly. A timestamp is good because it changes every time.
Code Implementation:
import groovy.beans.Bindable
import groovy.swing.SwingBuilder
import javax.swing.*
import java.awt.*
// Define the Model with a bindable property
class DataModel {
@Bindable String statusMessage = "Ready"
}
def model = new DataModel()
SwingBuilder.swingBuilder = new SwingBuilder()
// Building the UI on the Event Dispatch Thread (EDT)
swingBuilder.edt {
lookAndFeel('nimbus') // Make it look nice (optional)
frame(title: 'Groovy Reactive Binding',
size: [400, 200],
defaultCloseOperation: JFrame.EXIT_ON_CLOSE,
show: true) {
borderLayout()
// The Label: It's text is bound to the model's property
// When 'model.statusMessage' changes, this label updates automatically
label(text: bind(source: model, sourceProperty: 'statusMessage', converter: { it }),
id: 'statusLabel',
constraints: BorderLayout.CENTER,
horizontalAlignment: SwingConstants.CENTER)
// The Button: Updates the model on click
button(text: 'Update Status',
constraints: BorderLayout.SOUTH,
actionPerformed: {
model.statusMessage = "Updated at ${new Date()}"
})
}
}
Reviewing the Binding Syntax:
The bind closure syntax bind { model.statusMessage } is the most "Groovy" way to do it, though source and sourceProperty are more explicit.
bind { model.statusMessage } is shorthand.
Also, edt is crucial.
Let's verify the @Bindable mechanism.
When @Bindable is added to a field, Groovy adds PropertyChangeSupport to the class and fires events in the setter.
SwingBuilder's bind() listens for these events.
The prompt asks for a "reactive UI". This is a classic example of the Observer pattern implemented via Groovy's Metaprogramming and SwingBuilder.
Final Polish of the Code: I will structure the answer by providing:
@Bindable, bind, SwingBuilder).I should make sure the code handles the EDT correctly using SwingUtilities.invokeLater or builder.edt. builder.edt is cleaner.
One tricky thing in modern Groovy: groovy.beans.Bindable might need an import, but groovy.swing.SwingBuilder is standard.
Let's write the actual output based on this thought process. I'll use a simple counter logic for clarity in the model update.
import groovy.beans.Bindable
import groovy.swing.SwingBuilder
import javax.swing.*
import java.awt.*
// 1. The Model
// The @Bindable annotation injects java.beans.PropertyChangeSupport
// into the class automatically.
class ViewModel {
@Bindable String message = "Click the button to update me."
}
def model = new ViewModel()
// 2. The View
// SwingBuilder creates the UI declaratively.
new SwingBuilder().edt {
frame(title: "Reive Binding Example",
size: [400, 200],
defaultCloseOperation: JFrame.EXIT_ON_CLOSE,
visible: true) {
borderLayout()
// Label is bound to the model.
// When 'model.message' changes, the text updates automatically.
label(text: bind { model.message },
constraints: BorderLayout.CENTER,
horizontalAlignment: JLabel.CENTER)
// Button action modifies the model directly.
button(text: "Click to Update",
constraints: BorderLayout.SOUTH,
actionPerformed: {
model.message = "Updated at ${new Date().format('HH:mm:ss')}"
})
}
}
This looks correct and covers all requirements.
@Bindable.I will present the code clearly. I'll also add a small explanation about how @Bindable and bind work together, as that is the "magic" part of the request.
Double check: Does the user need groovy-all dependency info? Usually, for a script, just the code is enough, but running it requires Groovy installed. I'll assume the user knows how to run a Groovy script.
One specific detail: bind { model.message } uses the bind node in SwingBuilder? Yes. Actually, within SwingBuilder methods, bind is a helper method.
Wait, bind { model.message } inside a label text attribute.
text: bind { model.message } creates a binding.
When model fires a property change for message, the closure re-evaluates, and the label text updates.
Is bind available directly? Yes, SwingBuilder provides it.
Final check on imports.
groovy.beans.Bindable is needed.
groovy.swing.SwingBuilder is needed.
javax.swing.* and java.awt.* for layout and constants.
I'll write the final response now.
Here is a complete Groovy script that implements a reactive UI using SwingBuilder.
This example uses the Model-View-Controller (MVC) pattern inherent to Groovy's bind mechanism. We use the @Bindable annotation to automatically make the model reactive (observable), ensuring that when the data changes, the UI updates immediately.
Save this code in a file named ReactiveUI.groovy and run it.
import groovy.swing.SwingBuilder
import groovy.beans.Bindable
import javax.swing.*
import java.awt.*
// 1. THE MODEL
// The @Bindable annotation transforms this class.
// It adds PropertyChangeSupport automatically, allowing the UI to 'listen' to changes.
class MessageModel {
@Bindable String message = "Waiting for click..."
}
// 2. THE VIEW & CONTROLLER
def model = new MessageModel()
new SwingBuilder().edt { // edt ensures UI creation happens on the Event Dispatch Thread
frame(title: "Reive Binding Demo",
size: [400, 200],
defaultCloseOperation: JFrame.EXIT_ON_CLOSE,
visible: true) {
// Use BorderLayout for simple positioning
borderLayout()
// Label is bound to the model.
// syntax: bind(source: model, sourceProperty: 'propertyName')
// Whenever 'model.message' changes, this label's text updates automatically.
label(text: bind { model.message },
constraints: BorderLayout.CENTER,
horizontalAlignment: JLabel.CENTER,
font: font.deriveFont(Font.BOLD, 16))
// Button modifies the model, not the UI directly.
button(text: "Update Message",
constraints: BorderLayout.SOUTH,
actionPerformed: {
// Simulate a reactive data change
model.message = "Updated at ${new Date().format('HH:mm:ss')}"
})
}
}
@Bindable: This is the magic ingredient. When applied to a field in a Groovy class, it generates the necessary boilerplate code (getters/setters that fire PropertyChangeEvent) to make the object observable.bind { ... }: Inside the SwingBuilder, the bind method creates a link between the UI component and the data source.
bind { model.message }. This creates a closure that monitors the model object.actionPerformed closure.model.message.@Bindable, the model fires an event.Assuming you have Groovy installed, you can run this directly from your terminal:
groovy ReactiveUI.groovy