Reputation: 2280
I'm trying to make a really simple text input field (to replicate later for a more complex purpose). Using IDEA 14 CE, not sure it matters. I wrote this code:
import groovy.swing.SwingBuilder
import groovy.beans.Bindable
import static javax.swing.JFrame.EXIT_ON_CLOSE
import java.awt.*
String word
@Bindable
class UserInput {
String word
//String toString() { "$word" }
}
def userInput = new UserInput(word: null)
def swingBuilder = new SwingBuilder()
swingBuilder.edt {
lookAndFeel 'nimbus'
// frame size
def width = 350
def height = 230
frame (
title: 'Input',
size: [width, height],
show: true,
locationRelativeTo: null,
defaultCloseOperation: EXIT_ON_CLOSE ) {
borderLayout(vgap: 5)
panel(constraints:
BorderLayout.CENTER,
border: compoundBorder([emptyBorder(10), titledBorder('Input:')]))
{
tableLayout {
tr {
td { label 'Input: ' }
td { textField userInput.word, id: userInput.word, columns: 20 }
}
}
}
panel(constraints: BorderLayout.SOUTH) {
button text: 'Print word', actionPerformed: {
println """Word: ${userInput.word}"""
}
}
}
}
When I run it, I get this Swing box:
No matter what I input, when I click Print Word it always prints:
Word: null
What am I doing wrong? Seems like I am failing to assign user input to a parameter or something like that, but I cannot figure it out.
Upvotes: 0
Views: 68
Reputation: 171164
Right, you need to use bean binding to get the text property of the textField bound to your model. This works:
import groovy.swing.SwingBuilder
import groovy.beans.Bindable
import static javax.swing.JFrame.EXIT_ON_CLOSE
import java.awt.*
String word
@Bindable
class UserInput {
String word
}
def userInput = new UserInput(word: null)
def swingBuilder = new SwingBuilder().edt {
lookAndFeel 'nimbus'
// frame size
def width = 350
def height = 230
frame (title: 'Input',
size: [width, height],
show: true,
locationRelativeTo: null ) {
borderLayout(vgap: 5)
panel(constraints: BorderLayout.CENTER,
border: compoundBorder([emptyBorder(10), titledBorder('Input:')])) {
tableLayout {
tr {
td { label 'Input: ' }
td { textField id:'input', columns: 20 }
}
}
}
panel(constraints: BorderLayout.SOUTH) {
button text: 'Print word', actionPerformed: {
println """Word: ${userInput.word}"""
}
}
// Bind the text field to the bean
bean userInput, word: bind { input.text }
}
}
Upvotes: 2