Groovy SwingBuilder:用于更改面板颜色的按钮

|| 为什么此代码失败? 我想更改一系列动态构建的面板中的一个面板的颜色(事先未知的面板总数)。 出于某种原因,该代码在引用特定面板的名称(例如\'panel2 \')时有效,但在我动态引用它(\'panelID \')时则无效。
import groovy.swing.SwingBuilder
import javax.swing.WindowConstants as WC
import javax.swing.JOptionPane
import javax.swing.BoxLayout as BXL

swing = new SwingBuilder()
frame = swing.frame(title:\'test\',
    defaultCloseOperation:WC.DISPOSE_ON_CLOSE) {

    panel(id:\'mainPanel\'){
        def panelID 

        (1..6).each {
            panelID = \'panel\' + it

            panel(alignmentX: 0f, id: panelID , opaque:true ,background : java.awt.Color.GREEN){
                label(\'description\') 
                textField(id: \"description$it\", text: panelID, columns: 70 )
                button(id: \"button$panelID\", text: panelID, actionPerformed : {
                    panelID.background = java.awt.Color.RED
                    panelID.repaint()                       
                })
            }
        }
        boxLayout(axis: BXL.Y_AXIS)

        panel(id:\'secondPanel\' , alignmentX: 0f){                       
            button(\'Quit\', actionPerformed:{
                dispose()
            })
        }
    }       
}
frame.pack()
frame.show()
    
已邀请:
        要基于其ID获得元素,您需要将ID作为SwingBuilder的参数进行访问,如下所示:
import groovy.swing.SwingBuilder
import javax.swing.WindowConstants as WC
import javax.swing.JOptionPane
import javax.swing.BoxLayout as BXL

swing = new SwingBuilder()
frame = swing.frame(title:\'test\', pack:true, visible:true, defaultCloseOperation:WC.DISPOSE_ON_CLOSE) {
    panel(id:\'mainPanel\'){
        (1..6).each { num ->
            def panelID = \"panel$num\"
            def pane = panel( alignmentX:0f, id:panelID, background:java.awt.Color.GREEN ) {
                label(\'description\') 
                textField(id: \"description$num\", text:panelID, columns: 70 )
                button(id: \"buttonpanel$num\", text:panelID, actionPerformed : {
                    swing.\"$panelID\".background = java.awt.Color.RED
                })
            }
        }
        boxLayout(axis: BXL.Y_AXIS)

        panel(id:\'secondPanel\' , alignmentX: 0f){                       
            button(\'Quit\', actionPerformed:{
                frame.visible = false
            })
        }
    }       
}
    

要回复问题请先登录注册