Sunday, May 1, 2011

Groovy: How to access objects with Id tag?

Hello,

I have the following Groovy+SwingBuilder code.

In one panel I generate checkboxes and in another panel I want to access the values of the checkboxes. The code looks basically likes this:

   def optionsmap = [ foo : "value_foo",
                      bar : "value_bar"]

   SwingBuilder.build()     
   {
     frame(title:'demo1', size:[400,700], 
           visible:true, defaultCloseOperation:WC.EXIT_ON_CLOSE) {                
       gridLayout(rows: 1, cols: 2)

       panel(id:'optionPanel', constraints:java.awt.BorderLayout.CENTER) {                     
              gridLayout(rows: 5, cols: 1)           
       myGroup = buttonGroup();    
       for (entry in optionsmap)
       {     
         checkBox(id: entry.key,   text: entry.value        )               
       }        
       }

       panel(constraints:java.awt.BorderLayout.WEST) { 

          button ('Show values', actionPerformed: {          
          for (entry in optionsmap)
            {
               println (entry.key as Class).text    
            }         
          })            
       }
     }  
   }

optionsmap is a map with (id, text) pairs that can be extended.

When I press "show values" I get an error message:

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'foo' with class 'java.lang.String' to class 'java.lang.Class'

How could I access the checkboxes for my action in the second panel by using the checkbox ids from optionsmap?

Thank you if you can help

From stackoverflow
  • The solution to access variables from the map is like this:

    
                     for (entry in optionsmap)
                     {
                          if (variables[entry.key].selected)
                          println variables[entry.key].text
          }
    
  • This does not work. the variables is set to null and hence the program is throwing nullpointer exception

0 comments:

Post a Comment