Building Swing apps with Groovy

I’ve been playing around with Groovy for a couple of daya now, and wanted to try out the markup feature in the language to build data with nested structures (XML, HTML etc. The same Builder concept in Groovy applies to Swing apps as well, as a Swing app is constructed from nested components.

Here is a simple Swing app that is a file editor:

<code>
import groovy.swing.SwingBuilder
import java.awt.BorderLayout

def swing = new SwingBuilder()
def fileName

def widget = swing.frame(title:'GroovyEdit', size:[300,200], defaultCloseOperation:javax.swing.WindowConstants.EXIT_ON_CLOSE) 
{
    menuBar()
    {
        menu(text:'File')
        {
            menuItem(text:'New')
            separator()
            menuItem(text:'Save', actionPerformed:
            {
                if(fileName == null)
                {
                    fileDialog = swing.fileChooser()
       	            fileChoice = fileDialog.showSaveDialog()
	            if(fileChoice == fileDialog.APPROVE_OPTION)
	            {
	                fileName = fileDialog.selectedFile.absolutePath
	                println(fileName)
	            }
	        }
	        new File(fileName).withWriter{ w | w.write(editorText.text) }
	    })
            
            separator()
            menuItem(text:'Exit', actionPerformed:{ System.exit(0) })
        }
    }
    panel(layout: new BorderLayout()) {
          editorText = textArea(constraints: BorderLayout.CENTER)
       }
}
widget.show()

</code>

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.