如何在Groovy中将字符串转为SwingBuilder变量以调用组件文本
Got it, let's figure this out! When you're working with Groovy's SwingBuilder, the components you create (like your text fields with IDs date and name) are registered in the builder's internal widget store. Groovy's dynamic nature lets you access these components using string-based names without needing any fancy reflection hacks.
核心思路
Instead of trying to treat the string variable name as a direct variable, you can use Groovy's dynamic property access syntax with your SwingBuilder instance. This lets you fetch the component by its ID string, then access its text property like normal.
完整代码示例
Here's a concrete example that matches your scenario:
import groovy.swing.SwingBuilder import java.awt.BorderLayout def builder = new SwingBuilder() // Build your UI with text fields assigned IDs builder.frame(title: "Dynamic Component Access", size: [300, 150], visible: true) { borderLayout() panel(constraints: BorderLayout.CENTER) { gridLayout(rows: 2, cols: 2) label(text: "Date:") textField(id: "date", text: "2024-05-20") // ID matches your string label(text: "Name:") textField(id: "name", text: "Might Guy") // ID matches your string } } // Split your string to get component names def fieldNameStrings = "date;name".split(";") // Dynamically access each component and get its text fieldNameStrings.each { fieldName -> // Use builder."$fieldName" to fetch the component by string ID def component = builder."$fieldName" def inputText = component.text println "Value for $fieldName: $inputText" }
关键细节
- When you create a component with
id: "date"in SwingBuilder, the builder stores that component under thedateproperty. - The syntax
builder."$fieldName"is Groovy's way of dynamically accessing a property using a string. This works because Groovy supports runtime property resolution. - If you tried just using the string directly (like
date.textwithout the builder), that would fail because the string isn't a variable—you need to go through the builder to get the actual Swing component.
如果你遇到的是本地变量(不是builder注册的ID)
If you had defined components as local variables instead of using SwingBuilder's id parameter, you could access them via the script's binding:
def date = builder.textField(text: "2024-05-20") def name = builder.textField(text: "Might Guy") def fieldName = "date" def value = this."$fieldName".text println value // Outputs "2024-05-20"
But for SwingBuilder, using the id parameter and accessing via the builder instance is the standard, cleaner approach.
内容的提问来源于stack exchange,提问作者mightguy

