0
# GUI Building and Components
1
2
Core SwingBuilder functionality and factory system for declarative GUI construction using Groovy's builder pattern.
3
4
## Capabilities
5
6
### SwingBuilder Core
7
8
The primary builder class that orchestrates GUI construction through a comprehensive factory system.
9
10
```groovy { .api }
11
/**
12
* Primary declarative builder for creating Swing GUIs using Groovy's builder pattern
13
*/
14
class SwingBuilder extends FactoryBuilderSupport {
15
/** Constructor with optional initialization of default factories */
16
SwingBuilder(boolean init = true)
17
18
/** Execute closure on Event Dispatch Thread using invokeAndWait */
19
SwingBuilder edt(Closure c)
20
21
/** Execute closure on EDT using invokeLater */
22
SwingBuilder doLater(Closure c)
23
24
/** Execute closure outside EDT in separate thread */
25
SwingBuilder doOutside(Closure c)
26
27
/** Compatibility method for building GUIs */
28
Object build(Closure c)
29
30
/** Create keyboard shortcuts with platform-specific modifiers */
31
KeyStroke shortcut(key, modifier = 0)
32
KeyStroke shortcut(String key, modifier = 0)
33
34
/** Register key bindings for components */
35
void createKeyStrokeAction(Map attributes, JComponent component = null)
36
37
/** Factory method to create builder and run closure on EDT */
38
static SwingBuilder edtBuilder(Closure c)
39
40
/** Configure Look and Feel with various options */
41
static LookAndFeel lookAndFeel(Object... lafs)
42
static LookAndFeel lookAndFeel(Object laf, Closure initCode)
43
static LookAndFeel lookAndFeel(Map attributes, Object laf, Closure initCode)
44
}
45
```
46
47
**Usage Examples:**
48
49
```groovy
50
import groovy.swing.SwingBuilder
51
import javax.swing.*
52
53
// Basic builder creation and usage
54
def swing = new SwingBuilder()
55
def frame = swing.frame(title: 'My App') {
56
panel {
57
label(text: 'Hello World')
58
}
59
}
60
61
// Thread-safe EDT building
62
SwingBuilder.edtBuilder {
63
frame(title: 'EDT Safe', defaultCloseOperation: JFrame.EXIT_ON_CLOSE) {
64
button(text: 'Click Me')
65
}.show()
66
}
67
68
// Key stroke actions
69
swing.createKeyStrokeAction(
70
keyStroke: 'ctrl pressed N',
71
action: { println 'New file action' },
72
component: myPanel
73
)
74
75
// Platform shortcuts
76
def newShortcut = swing.shortcut(KeyEvent.VK_N) // Ctrl+N on Windows/Linux, Cmd+N on Mac
77
```
78
79
### Window Components
80
81
Factory classes for creating top-level windows and dialogs.
82
83
```groovy { .api }
84
// Frame creation with window management
85
frame(title: String, defaultCloseOperation: int = JFrame.HIDE_ON_CLOSE) { /* content */ }
86
87
// Dialog creation
88
dialog(title: String, modal: boolean = true, owner: Window = null) { /* content */ }
89
90
// Generic window
91
window(title: String, owner: Window = null) { /* content */ }
92
93
// Internal frames for MDI applications
94
internalFrame(title: String, closable: boolean = true, maximizable: boolean = true,
95
iconifiable: boolean = true, resizable: boolean = true) { /* content */ }
96
```
97
98
**Usage Examples:**
99
100
```groovy
101
// Main application frame
102
frame(title: 'My Application', defaultCloseOperation: JFrame.EXIT_ON_CLOSE,
103
size: [800, 600]) {
104
menuBar {
105
menu(text: 'File') {
106
menuItem(text: 'New', actionPerformed: { /* action */ })
107
menuItem(text: 'Open', actionPerformed: { /* action */ })
108
}
109
}
110
panel {
111
// main content
112
}
113
}
114
115
// Modal dialog
116
dialog(title: 'Settings', modal: true, size: [400, 300]) {
117
panel {
118
label(text: 'Configuration options:')
119
// form fields
120
}
121
}
122
```
123
124
### Action Widgets
125
126
Components that can be associated with Action objects for consistent behavior.
127
128
```groovy { .api }
129
// Buttons with action support
130
button(text: String, action: Action = null, actionPerformed: Closure = null)
131
checkBox(text: String, selected: boolean = false, action: Action = null)
132
radioButton(text: String, selected: boolean = false, action: Action = null)
133
toggleButton(text: String, selected: boolean = false, action: Action = null)
134
135
// Menu items with action support
136
menuItem(text: String, action: Action = null, actionPerformed: Closure = null)
137
checkBoxMenuItem(text: String, selected: boolean = false, action: Action = null)
138
radioButtonMenuItem(text: String, selected: boolean = false, action: Action = null)
139
```
140
141
**Usage Examples:**
142
143
```groovy
144
// Button with closure action
145
button(text: 'Save', actionPerformed: { e ->
146
// save logic here
147
println 'Document saved'
148
})
149
150
// Shared action for multiple components
151
def exitAction = swing.action(
152
name: 'Exit',
153
shortDescription: 'Exit the application',
154
accelerator: swing.shortcut('alt F4'),
155
closure: { System.exit(0) }
156
)
157
158
menuItem(action: exitAction)
159
button(action: exitAction)
160
```
161
162
### Text Components
163
164
Factory classes for text input and display components.
165
166
```groovy { .api }
167
// Text input components
168
textField(text: String = '', columns: int = 0, editable: boolean = true)
169
passwordField(text: String = '', columns: int = 0, echoChar: char = '*')
170
textArea(text: String = '', rows: int = 0, columns: int = 0, lineWrap: boolean = false)
171
textPane(text: String = '', editable: boolean = true, contentType: String = 'text/plain')
172
editorPane(text: String = '', editable: boolean = true, contentType: String = 'text/plain')
173
174
// Formatted text field with input validation
175
formattedTextField(value: Object = null, format: Format = null, columns: int = 0)
176
177
// Display components
178
label(text: String = '', icon: Icon = null, horizontalAlignment: int = SwingConstants.LEFT)
179
```
180
181
**Usage Examples:**
182
183
```groovy
184
// Text input form
185
panel {
186
label(text: 'Name:')
187
textField(id: 'nameField', columns: 20)
188
189
label(text: 'Password:')
190
passwordField(id: 'passwordField', columns: 20)
191
192
label(text: 'Comments:')
193
scrollPane {
194
textArea(id: 'commentsArea', rows: 5, columns: 30, lineWrap: true)
195
}
196
}
197
198
// Formatted number input
199
formattedTextField(
200
value: 0.0,
201
format: new DecimalFormat('#,##0.00'),
202
columns: 10
203
)
204
```
205
206
### Container Components
207
208
Components that can contain other components with various layout strategies.
209
210
```groovy { .api }
211
// Basic containers
212
panel(layout: LayoutManager = new FlowLayout())
213
scrollPane(horizontalScrollBarPolicy: int = JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED,
214
verticalScrollBarPolicy: int = JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED)
215
216
// Specialized containers
217
tabbedPane(tabPlacement: int = JTabbedPane.TOP)
218
splitPane(orientation: int = JSplitPane.HORIZONTAL_SPLIT,
219
continuousLayout: boolean = false, dividerLocation: int = -1)
220
toolBar(orientation: int = JToolBar.HORIZONTAL, floatable: boolean = true)
221
222
// Layered containers
223
layeredPane()
224
viewport()
225
```
226
227
**Usage Examples:**
228
229
```groovy
230
// Tabbed interface
231
tabbedPane {
232
panel(title: 'General') {
233
// general settings
234
}
235
panel(title: 'Advanced') {
236
// advanced settings
237
}
238
}
239
240
// Split pane layout
241
splitPane(orientation: JSplitPane.HORIZONTAL_SPLIT, dividerLocation: 200) {
242
scrollPane {
243
tree(id: 'fileTree')
244
}
245
scrollPane {
246
textArea(id: 'contentArea')
247
}
248
}
249
```
250
251
### Data Components
252
253
Components for displaying and editing structured data.
254
255
```groovy { .api }
256
// List component with model support
257
list(listData: Object[] = null, model: ListModel = null,
258
selectionMode: int = ListSelectionModel.SINGLE_SELECTION)
259
260
// Combo box with data binding
261
comboBox(items: Object[] = null, model: ComboBoxModel = null, editable: boolean = false)
262
263
// Table with comprehensive model support
264
table(model: TableModel = null, columnModel: TableColumnModel = null,
265
selectionModel: ListSelectionModel = null, autoCreateColumnsFromModel: boolean = true)
266
267
// Tree component
268
tree(model: TreeModel = null, rootVisible: boolean = true, showsRootHandles: boolean = false)
269
270
// Selection components
271
colorChooser(color: Color = Color.WHITE)
272
fileChooser(currentDirectory: File = null, fileSelectionMode: int = JFileChooser.FILES_ONLY)
273
```
274
275
**Usage Examples:**
276
277
```groovy
278
// Data table with custom model
279
table {
280
tableModel(list: myDataList) {
281
propertyColumn(header: 'Name', propertyName: 'name')
282
propertyColumn(header: 'Age', propertyName: 'age', type: Integer)
283
closureColumn(header: 'Full Info') { row ->
284
"${row.name} (${row.age})"
285
}
286
}
287
}
288
289
// Combo box with items
290
comboBox(items: ['Option 1', 'Option 2', 'Option 3'],
291
selectedIndex: 0,
292
actionPerformed: { e ->
293
println "Selected: ${e.source.selectedItem}"
294
})
295
```
296
297
### Utility Components
298
299
Various utility components for enhanced user interfaces.
300
301
```groovy { .api }
302
// Value selection components
303
slider(minimum: int = 0, maximum: int = 100, value: int = 50,
304
orientation: int = JSlider.HORIZONTAL, majorTickSpacing: int = 0)
305
spinner(model: SpinnerModel = new SpinnerNumberModel(), value: Object = null)
306
progressBar(minimum: int = 0, maximum: int = 100, value: int = 0,
307
orientation: int = JProgressBar.HORIZONTAL, stringPainted: boolean = false)
308
309
// Separation components
310
separator(orientation: int = JSeparator.HORIZONTAL)
311
scrollBar(orientation: int = JScrollBar.VERTICAL, minimum: int = 0, maximum: int = 100)
312
313
// Special components
314
desktopPane()
315
optionPane(message: Object = null, messageType: int = JOptionPane.INFORMATION_MESSAGE)
316
```
317
318
**Usage Examples:**
319
320
```groovy
321
// Settings panel with various controls
322
panel {
323
label(text: 'Volume:')
324
slider(minimum: 0, maximum: 100, value: 50, majorTickSpacing: 25,
325
paintTicks: true, paintLabels: true)
326
327
separator()
328
329
label(text: 'Count:')
330
spinner(model: new SpinnerNumberModel(1, 1, 100, 1))
331
}
332
```
333
334
### Image and Icon Support
335
336
Factory for creating and managing icons and images.
337
338
```groovy { .api }
339
// Image icon creation
340
imageIcon(url: URL = null, filename: String = null, resource: String = null,
341
image: Image = null, description: String = null)
342
```
343
344
**Usage Examples:**
345
346
```groovy
347
// Button with icon
348
button(text: 'Open File',
349
icon: imageIcon(resource: '/icons/open.png'),
350
actionPerformed: { /* open file */ })
351
352
// Label with image
353
label(icon: imageIcon(filename: 'logo.png'),
354
horizontalAlignment: SwingConstants.CENTER)
355
```