NicolasB NicolasB - 6 months ago 50
Groovy Question

Groovy: Altering text of button when pressed

I am looking for a way to change the text of a button in Groovy when it is clicked. I can't find any documentation on it. I'm using Swingbuilder to lay the buttons out (it is for a Battleship game). I'm fairly new at using this lang.

What I'm using is:

import groovy.swing.SwingBuilder
import javax.swing.*
import java.awt.BorderLayout


class FrontEnd {
FrontEnd() {
def builder = new SwingBuilder()
builder.edt {
frame(title: 'Battleship', size: [500, 350], show: true, locationRelativeTo: null, resizable: false,
defaultCloseOperation: WindowConstants.EXIT_ON_CLOSE) {

borderLayout(vgap: 5)

panel(constraints: BorderLayout.CENTER) {
tableLayout {
tr {...
}
tr {
td {
label '1'
}
td {
button(id: 'a1', text: ' ', actionPerformed:)
}
td {
button(id: 'b1', text: ' ', actionPerformed:)
}


I don't know if it is even possible with this setup, so if there is another way I'd be glad to know about it.

Thank you.

Answer Source

The following example assigns a button to the variable myButton which is then used for reference. Clicking on the button will set the text to hello 0, hello 1, etc:

import groovy.swing.SwingBuilder 
import groovy.beans.Bindable 
import static javax.swing.JFrame.EXIT_ON_CLOSE 
import java.awt.*

class Example {
    static def count = 0

    static void main(String[] args) {
        def swingBuilder = new SwingBuilder()
        swingBuilder.edt {  
            frame(title: 'Example', size: [140, 80],
                  show: true, locationRelativeTo: null,
                  defaultCloseOperation: EXIT_ON_CLOSE) {
                borderLayout(vgap: 5)

                panel(constraints: BorderLayout.SOUTH) {
                    myButton = button text: 'Save', actionPerformed: {
                        myButton.setText("hello ${count++}")
                    }
                }
            } 
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download