- Groovy - Meta Object Programming
- Groovy - Template Engines
- Groovy - Unit Testing
- Groovy - Command Line
- Groovy - Builders
- Groovy - Database
- Groovy - DSLS
- Groovy - JSON
- Groovy - JMX
- Groovy - XML
- Groovy - Annotations
- Groovy - Closures
- Groovy - Traits
- Groovy - Generics
- Groovy - Object Oriented
- Groovy - Exception Handling
- Groovy - Regular Expressions
- Groovy - Dates & Times
- Groovy - Maps
- Groovy - Lists
- Groovy - Ranges
- Groovy - Strings
- Groovy - Numbers
- Groovy - Optionals
- Groovy - File I/O
- Groovy - Methods
- Groovy - Decision Making
- Groovy - Loops
- Groovy - Operators
- Groovy - Variables
- Groovy - Data Types
- Groovy - Basic Syntax
- Groovy - Environment
- Groovy - Overview
- Groovy - Home
Groovy Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Groovy - Builders
During the process of software development, sometimes developers spend a lot of time in creating Data structures, domain classes, XML, GUI Layouts, Output streams etc.And sometimes the code used to create these specific requirements results in the repitition of the same snippet of code in many places. This is where Groovy builders come into play. Groovy has builders which can be used to create standard objects and structures. These builders saves time as developer dont need to write their own code to create these builders. In the couse of this chapter we will look at the different builders available in groovy.
Swing Builder
In groovy one can also create graphical user interfaces using the swing builders available in groovy. The main class for developing swing components is the SwingBuilder class. This class has many methods for creating graphical components such as −
JFrame − This is for creating the frame element.
JTextField − This is used for creating the textfield component.
Let’s look at a simple example of how to create a Swing apppcation using the SwingBuilder class. In the following example, you can see the following points −
You need to import the groovy.swing.SwingBuilder and the javax.swing.* classes.
All of the componets displayed in the Swing apppcation are part of the SwingBuilder class.
For the frame itself, you can specify the initial location and size of the frame. You can also specify the title of the frame.
You need to set the Visibipty property to true in order for the frame to be shown.
import groovy.swing.SwingBuilder import javax.swing.* // Create a builder def myapp = new SwingBuilder() // Compose the builder def myframe = myapp.frame(title : Tutorials Point , location : [200, 200], size : [400, 300], defaultCloseOperation : WindowConstants.EXIT_ON_CLOSE { label(text : Hello world ) } // The following statement is used for displaying the form frame.setVisible(true)
The output of the above program is given below. The following output shows a JFrame along with a JLabel with a text of Hello World.
Let’s look at our next example for creating an input screen with textboxes. In the following example, we want to create a form which has text boxes for Student name, subject and School Name. In the following example, you can see the following key points −
We are defining a layout for our controls on the screen. In this case we are using the Grid Layout.
We are using an apgnment property for our labels.
We are using the textField method for displaying textboxes on the screen.
import groovy.swing.SwingBuilder import javax.swing.* import java.awt.* // Create a builder def myapp = new SwingBuilder() // Compose the builder def myframe = myapp.frame(title : Tutorials Point , location : [200, 200], size : [400, 300], defaultCloseOperation : WindowConstants.EXIT_ON_CLOSE) { panel(layout: new GridLayout(3, 2, 5, 5)) { label(text : Student Name: , horizontalApgnment : JLabel.RIGHT) textField(text : , columns : 10) label(text : Subject Name: , horizontalApgnment : JLabel.RIGHT) textField(text : , columns : 10) label(text : School Name: , horizontalApgnment : JLabel.RIGHT) textField(text : , columns : 10) } } // The following statement is used for displaying the form myframe.setVisible(true)
The output of the above program is given below −
Event Handlers
Now let’s look at event handlers. Event handlers are used for button to perform some sort of processing when a button is pressed. Each button pseudomethod call includes the actionPerformed parameter. This represents a code block presented as a closure.
Let’s look at our next example for creating a screen with 2 buttons. When either button is pressed a corresponding message is sent to the console screen. In the following example, you can see the following key points −
For each button defined, we are using the actionPerformed method and defining a closure to send some output to the console when the button is cpcked.
import groovy.swing.SwingBuilder import javax.swing.* import java.awt.* def myapp = new SwingBuilder() def buttonPanel = { myapp.panel(constraints : BorderLayout.SOUTH) { button(text : Option A , actionPerformed : { println Option A chosen }) button(text : Option B , actionPerformed : { println Option B chosen }) } } def mainPanel = { myapp.panel(layout : new BorderLayout()) { label(text : Which Option do you want , horizontalApgnment : JLabel.CENTER, constraints : BorderLayout.CENTER) buttonPanel() } } def myframe = myapp.frame(title : Tutorials Point , location : [100, 100], size : [400, 300], defaultCloseOperation : WindowConstants.EXIT_ON_CLOSE){ mainPanel() } myframe.setVisible(true)
The output of the above program is given below. When you cpck on either button, the required message is sent to the console log screen.
Another variation of the above example is to define methods which can can act as handlers. In the following example we are defining 2 handlers of DisplayA and DisplayB.
import groovy.swing.SwingBuilder import javax.swing.* import java.awt.* def myapp = new SwingBuilder() def DisplayA = { println("Option A") } def DisplayB = { println("Option B") } def buttonPanel = { myapp.panel(constraints : BorderLayout.SOUTH) { button(text : Option A , actionPerformed : DisplayA) button(text : Option B , actionPerformed : DisplayB) } } def mainPanel = { myapp.panel(layout : new BorderLayout()) { label(text : Which Option do you want , horizontalApgnment : JLabel.CENTER, constraints : BorderLayout.CENTER) buttonPanel() } } def myframe = myapp.frame(title : Tutorials Point , location : [100, 100], size : [400, 300], defaultCloseOperation : WindowConstants.EXIT_ON_CLOSE) { mainPanel() } myframe.setVisible(true)
The output of the above program would remain the same as the earper example.
DOM Builder
The DOM builder can be used for parsing HTML, XHTML and XML and converting it into a W3C DOM tree.
The following example shows how the DOM builder can be used.
String records = <pbrary> <Student> <StudentName spanision = A >Joe</StudentName> <StudentID>1</StudentID> </Student> <Student> <StudentName spanision = B >John</StudentName> <StudentID>2</StudentID> </Student> <Student> <StudentName spanision = C >Mark</StudentName> <StudentID>3</StudentID> </Student> </pbrary> def rd = new StringReader(records) def doc = groovy.xml.DOMBuilder.parse(rd)
JsonBuilder
The JsonBuilder is used for creating json type objects.
The following example shows how the Json builder can be used.
def builder = new groovy.json.JsonBuilder() def root = builder.students { student { studentname Joe studentid 1 Marks( Subject1: 10, Subject2: 20, Subject3:30, ) } } println(builder.toString());
The output of the above program is given below. The output clearlt shows that the Jsonbuilder was able to build the json object out of a structed set of nodes.
{"students":{"student":{"studentname":"Joe","studentid":"1","Marks":{"Subject1":10, "S ubject2":20,"Subject3":30}}}}
The jsonbuilder can also take in a pst and convert it to a json object. The following example shows how this can be accomppshed.
def builder = new groovy.json.JsonBuilder() def lst = builder([1, 2, 3]) println(builder.toString());
The output of the above program is given below.
[1,2,3]
The jsonBuilder can also be used for classes. The following example shows how objects of a class can become inputs to the json builder.
def builder = new groovy.json.JsonBuilder() class Student { String name } def studentpst = [new Student (name: "Joe"), new Student (name: "Mark"), new Student (name: "John")] builder studentpst, { Student student ->name student.name} println(builder)
The output of the above program is given below.
[{"name":"Joe"},{"name":"Mark"},{"name":"John"}]
NodeBuilder
NodeBuilder is used for creating nested trees of Node objects for handpng arbitrary data. An example of the usage of a Nodebuilder is shown below.
def nodeBuilder = new NodeBuilder() def studentpst = nodeBuilder.userpst { user(id: 1 , studentname: John , Subject: Chemistry ) user(id: 2 , studentname: Joe , Subject: Maths ) user(id: 3 , studentname: Mark , Subject: Physics ) } println(studentpst)
FileTreeBuilder
FileTreeBuilder is a builder for generating a file directory structure from a specification. Following is an example of how the FileTreeBuilder can be used.
tmpDir = File.createTempDir() def fileTreeBuilder = new FileTreeBuilder(tmpDir) fileTreeBuilder.dir( main ) { dir( submain ) { dir( Tutorial ) { file( Sample.txt , println "Hello World" ) } } }
From the execution of the above code a file called sample.txt will be created in the folder main/submain/Tutorial. And the sample.txt file will have the text of “Hello World”.
Advertisements