无法获得输出不为空

时间:2015-06-27 08:21:31

标签: swing groovy

我正在尝试创建一个非常简单的文本输入字段(稍后为了更复杂的目的而复制)。使用IDEA 14 CE,不确定是否重要。我写了这段代码:

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}"""
            }
        }
    }
}

当我运行它时,我得到了这个Swing框:

box

无论我输入什么,当我点击打印Word 时,它总会打印出来:

Word: null

我做错了什么?似乎我没有将用户输入分配给参数或类似的东西,但我无法弄明白。

1 个答案:

答案 0 :(得分:2)

是的,您需要使用bean绑定来获取绑定到模型的textField的text属性。这有效:

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 }
    }
}