Introduction to Groovy
This document gets you started
with Groovy in NetBeans IDE. You will
create a Java application, add a JFrame, and retrieve a simple message from
a Groovy file.
Contents
To follow this tutorial, you need the following software and resources.
Creating the Application
In this section, we create a Java application.
- Choose File > New Project (Ctrl-Shift-N) and then select "Java Application" from
the "Java" category.

Click Next.
- In Project Name, type "GroovyJavaDemo"; in Project Location, select the folder
where the application will be created.

Make sure to unselect the Create Main Class checkbox. Click Finish.
Creating the Java Class and the Groovy File
In this section, we create a JFrame and a Groovy class.
- Right-click the project and choose New | Other. In the New File dialog,
choose Swing GUI Forms | JFrame Form. In Class Name, type "DisplayJFrame";
in Package, type "org.demo":

Click Finish. The JFrame is created.
- Open the New File dialog again and choose Groovy | Groovy Class:

Click Next.
- In Class Name, type GreetingProvider; in Package, select the package
you created previously:

Click Finish. The Groovy file is created. Your project structure should now be as follows:

Calling Groovy from Java
In this section, we code the interaction between the Groovy file and the Java class.
- In the Groovy class, define a greeting variable within the class definition,
as shown below:
class GreetingProvider {
def greeting = "Hello from Groovy"
}
- Open the DisplayJFrame class in the editor. In the design view, drag and drop a JTextField into the JFrame.

- Switch to the Source view
of the JFrame. In the top of the class body, instantiate the Groovy class. In the constructor, call the groovy class' getGreeting() method, as shown below:
public class DisplayJFrameForm extends javax.swing.JFrame {
GreetingProvider provider = new GreetingProvider();
public DisplayJFrame() {
initComponents();
String greeting = provider.getGreeting().toString();
jTextField1.setText(greeting);
}
- You can use code completion in the Java class
to find the methods you need in the Groovy class:

- Run the application and the text from the Groovy class is shown in the JFrame:

You now know how to create a basic Java application
that interacts with Groovy.
See Also
NetBeans IDE also supports the Grails web framework, which uses the Groovy language
in Java web development. To learn how to use the Grails framework with NetBeans IDE,
see Introduction to the Grails Framework.