corner imagecorner image
IDEPlatformPluginsDocs & SupportCommunityPartners

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

Content on this page applies to NetBeans IDE 6.5, 6.7 and 6.8

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required
NetBeans IDE version 6.5 Java or above
Java Development Kit (JDK) version 6 or
version 5

Creating the Application

In this section, we create a Java application.

  1. Choose File > New Project (Ctrl-Shift-N) and then select "Java Application" from the "Java" category.

    Creating a new app

    Click Next.

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

    Creating a new app

    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.

  1. 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":

    Creating a new app

    Click Finish. The JFrame is created.

  2. Open the New File dialog again and choose Groovy | Groovy Class:

    Creating a new app

    Click Next.

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

    Creating a new app

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

    Creating a new app

Calling Groovy from Java

In this section, we code the interaction between the Groovy file and the Java class.

  1. In the Groovy class, define a greeting variable within the class definition, as shown below:
    class GreetingProvider {
    
        def greeting = "Hello from Groovy"
    
    }

  2. Add a JTextField to the JFrame. In the Source view of the JFrame, initialize the Groovy class and call its getGreeting() method, as shown below:
    GreetingProvider provider = new GreetingProvider();
    
    public DisplayJFrame() {
        initComponents();
        String greeting = provider.getGreeting().toString();
        jTextField1.setText(greeting);
    }

    Note: Issue 161176 covers the problem where there is an error underline when there shouldn't be, in the first line above. The application should still run successfully, however.

  3. You can use code completion in the Java class to find the methods you need in the Groovy class:

    Creating a new app

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

    Creating a new app

You now know how to create a basic Java application that interacts with Groovy.