Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java It Depends On You

Binyamin Friedman
Binyamin Friedman
14,615 Points

Gradle in JavaFX projects

Can Gradle be used with JavaFX projects? When you make a new project in IntelliJ you can only use one or the other. Tell me if I'm being unclear

2 Answers

I see what you mean, you're referring to the IntelliJ project templates.

The JavaFX project template simply creates a Main.java file and Controller.java file as well as a sample.fxml file. They're just files for a hello world app - you can make a JavaFX app without them.

Unfortunately, in IntelliJ, you have to create or import a project as a Gradle project to get the Gradle tool window. You can just start a new Gradle project and create your own Main and Controller classes and index.fxml and let Gradle handle compiling your source code.

If you want to make an executable binary, you can use Gradle's "application" plugin in addition to the "java" plugin (instead of running your app by entering java -jar my-app.jar you can simply run my-app).

If you do happen to want those JavaFX starter files, just copy these (use whatever package name you want, doesn't have to be the default "sample"):

Main.java

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

Controller.java

public class Controller {
}

sample.fxml

<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<GridPane fx:controller="Controller"
          xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
</GridPane>
Binyamin Friedman
Binyamin Friedman
14,615 Points

This question was asked a couple months ago and I understand that now, but thank you anyways!