Show a variable from Java thread in UI built with SwingBuilder

262 views Asked by At

java source:

class jview implements Runnable{
    public void run(){
        for(int i=1;i<10;i++){
            try {
                Thread.sleep(1000);
                System.out.println(i); // XXX show in UI
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args)throws Exception{     
        String[] roots = new String[] {"C:/Users/groovy"};
        GroovyScriptEngine gse = new GroovyScriptEngine(roots);
        Binding binding = new Binding();
        gse.run("gview.groovy", binding);
        jview j = new jview();
        Thread t = new Thread(j);
        t.start();
    }
}

groovy source:

def swingBuilder = new SwingBuilder()
swingBuilder.edt {
    frame(title: 'ex', size: [200, 150], show: true) {
        borderLayout(vgap: 5)
        panel(constraints: BorderLayout.CENTER, border: emptyBorder(10)) {
            label "java variable" // XXX value of `i`
        }
    }
}

How do I show the variable i from the Java thread in Swing UI (from Groovy).

1

There are 1 answers

0
jalopaba On

First, create a JTextField that is updated in your run method:

static JTextField textField = new JTextField("Init...", 5);

public void run() {
    for(int i = 1; i < 10; i++){
        try {
            Thread.sleep(1000);
            textField.setText(String.valueOf(i)); // Update UI
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Pass it in the script binding:

    GroovyScriptEngine gse = new GroovyScriptEngine(roots);
    Binding binding = new Binding();
    binding.setVariable("variableTextField", textField);
    gse.run("gview.groovy", binding);

Then, in the groovy code, you can use widget to "put" the textField in the builder:

swingBuilder.edt {   
    frame(title: 'ex', size: [200, 150], show: true, defaultCloseOperation: EXIT_ON_CLOSE) { 
        borderLayout(vgap: 5)

        panel(constraints: BorderLayout.CENTER, border: emptyBorder(10)) {
            tableLayout(cellpadding: 5) {
                tr {
                    td {
                        label 'Value'
                    }
                    td {
                        widget(variableTextField)
                    }
                }
            }           
        }
    }
}

Basically, with this you are doing in Java what the doOutside and setMessage do in Changing value in textfield with groovy and SwingBuilder.