Newer
Older
labs / tiddlywiki / tiddlers / content / labs / lab01 / _labs_lab01_Adding a Default Main Class.md

You have been running the Main class directly by explicitly selecting that class using the right mouse button. Remember that in Java, any class can have a main method. We will usually have one class that we consider to be the primary 'main' class that we want to run to start our application — we should tell Gradle which class we consider to be the 'main' class in our project.

First, let's explore what happens when we don't set a main class. Try to run the entire project using <

Run Project">>. You will probably find that the menu item is disabled since NetBeans recognises that this is not an executable project.

Add the following to the <> file. It should go inside the curly braces of the plugins section, below the existing line.

id 'application'

This tells Gradle that our project is now an executable application.

We also need to tell Gradle which class is the main class. Add the following to the bottom of the file below the plugins section (after the closing curly brace for that section).

mainClassName = 'lab01.Main'

The complete file should look like:

plugins {
    id 'java'
    id 'application'
}

mainClassName = 'lab01.Main'

Save the file, and left click on the root of the project — switching focus away from the file is enough to get NetBeans to reload the file which is why we are clicking the project root.

You should now be able to run the project using <

Run Project">>. The big green run button on the main tool bar will also run the project. You can also use the <> key to run the project.

If you ever find yourself in a situation where Gradle is running the wrong main method, or complaining about a missing file, then it is likely that you have the mainClassName property pointing to the wrong class.

You always have the option of explicitly right clicking a file in either the source editor, or the project pane and selecting <

> — NetBeans will tell Gradle to run this file instead of using the default main class. The shortcut key for running the currently selected file is < F6">>.