Создание проекта в IntelliJ IDEA
В этом уроке мы рассмотрим как создавать проект в Intellij IDEA.
Шаг 1: Запускаем Intellij IDEA. Если вы запускаете ее первый раз, то у вас появится такое окошко:
Выбираем пункт меню «Create New Project».
Если вы уже работали в ней, у вас откроется последний созданный проект. Для создания нового проекта выбираем меню File ->New ->Project:
Шаг 2: В открывшемся окошке выбираем пункт Java. В поле SDK выбираем нужную версию Java. Если вариантов нет, жмем кнопку New и ищем в файловой системе каталог, в который вы установили Java (jdk). И жмем Next.
Шаг 3: В следующем окошке можно выбрать шаблон, на основе которого будет создан проект (но это не обязательно). Ставим галочку в Create project from template и давайте выберем шаблон Command Line App. После чего опять же нажимаем Next.
Шаг 4: Выбираем имя вашего проекта в Intellij IDEA — «Project name». В поле «Project location» можно выбрать каталог в файловой системе вашего компьютера, куда будет сохранен проект. В поле «Base package» можно указать имя пакета, который будет создан. И в конце жмем кнопку Finish.
В общем все — ваш проект создался и открылся. В левом окошке Project вы можете увидеть структуру проекта:
В созданном проекте есть каталог src, в котором находятся пакетные каталоги com/company. А также создан класс Main.
Презентацию с видео можно скачать на Patreon .
Create a new project
This section describes the functionality available out of the box. If you are using a framework plugin, refer to the corresponding documentation section.
New project without frameworks
This is a general-purpose project without specific frameworks. You will be able to add the necessary frameworks and technologies later at any time.
- Launch IntelliJ IDEA. If the Welcome screen opens, click New Project . Otherwise, go to File | New | Project in the main menu.
- From the list on the left, select New Project .
- Name the new project and change its location if necessary.
- Select the Create Git repository checkbox to place the new project under version control. You will be able to do it later at any time.
- From the Language list, select the language that you want to use in your application. If you want to use a language that is not available in IntelliJ IDEA out of the box (for example, Python or PHP), click the button and select the necessary option. The IDE will open a dialog in which you can select and install the necessary language plugin. After that, you can close the dialog and keep configuring the new project.
- Select the build system that you want to use in your project: the native IntelliJ builder, Maven, or Gradle. For Gradle, you will also need to select a language for the build script: Groovy or Kotlin.
- From the JDK list, select the JDK that you want to use in your project. If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory. If you don’t have the necessary JDK on your computer, select Download JDK .
- Enable the Add sample code option to create a class with a sample HelloWorld application. Select the Generate code with onboarding tips option to create a basic sandbox project with tips demonstrating some of the IDE’s essential features.
Other languages
New Java project with onboarding tips
If you are new to IntelliJ IDEA, you can create a project with onboarding tips. This will get you a basic sandbox project with tips demonstrating some of the IDE’s essential features. Follow the small guide provided in the project to try the Search Everywhere functionality, apply a quick-fix, and run and debug the code.
- Launch IntelliJ IDEA. If the Welcome screen opens, click New Project . Otherwise, go to File | New | Project in the main menu.
- From the list on the left, select New Project . Select Java as the project language and configure the options as described in New project without frameworks.
- Select the Add sample code checkbox and enable Generate code with onboarding tips .
- Click Create .
As a result, IntelliJ IDEA create a project with sample code and onboarding information right in the editor.
New empty project
This is a basic project that allows you to work with different languages, Java or Kotlin classes without a predefined SDK, which could be useful for adhoc developing, creating mockups, and testing.
- Launch IntelliJ IDEA. Do one of the following:
- Click New Project on the Welcome screen.
- Select File | New | Project from the main menu.
- (Available in the new UI) Click the Project widget in the main window header and select New Project .
- From the list on the left, select Empty Project .
- Name the new project and change its location if necessary.
- Select the Create Git repository to place the new project under version control. You will be able to do it later at any time. The .gitignore file is generated in any case.
- Click Create .
New framework-based project
These are framework-based projects. Select one of the provided project types to create a project from a pre-defined template.
Maven Archetype
If you are creating a project using a Maven archetype, IntelliJ IDEA displays the Maven settings that you can use to set the Maven home directory and Maven repositories. Also, you can check the archetype properties.
Specify a name for your project.
Specify the path to the directory in which you want to create the project. By default, the IDE creates a directory with the same name as the project.
Create Git repository
Place the new project under version control.
You will be able to do it later at any time.
From the JDK list, select the JDK that you want to use in your project.
If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory.
If you don’t have the necessary JDK on your computer, select Download JDK .
Specify which Maven repository you want to use in your project.
The internal Maven catalog is a default one. You can also select the local repository that is located in the .m2 directory, or you can select Maven central repository.
Moreover, you can click Manage Catalogs and add a custom repository if you need.
Select the needed Maven archetype. Click Add to specify the custom archetype.
The version is specified automatically.
In this area, you can specify additional properties on top of the built-in ones
Specify the following Maven coordinates that are added to the pom.xml file:
- GroupId : a package of a new project.
- ArtifactId : a name of your project.
For more information about Maven coordinates, refer to Maven naming conventions.
For more information about creating a Maven-based project, refer to Maven.
Jakarta EE
For a step-by-step instruction on how to create a JavaEE project, refer to Tutorial: Your first Java EE application.
Specify a name for your project.
Specify the path to the directory in which you want to create the project. By default, the IDE creates a directory with the same name as the project.
Create Git repository
Place the new project under version control.
You will be able to do it later at any time.
Select a template for your application. IntelliJ IDEA will pre-configure your project accordingly.
Specify the application server that you want to use in this application.
IntelliJ IDEA provides integration with various application servers, enabling you to start and stop local servers, connect to running remote servers, and deploy your artifacts on those servers.
Select the language that you want to use in your application.
Select the build tool that will be used for managing dependencies, testing, packaging, automating the build process, and so on.
Specify the unique group identifier for your project. It should preferably start with the reversed domain name you control (for example, com.example ).
From the JDK list, select the JDK that you want to use in your project.
If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory.
If you don’t have the necessary JDK on your computer, select Download JDK .
Select the Java EE version that you want to use.
Select the technologies, frameworks and languages that you want your project to support.
Spring Initializr
For more information about creating a Spring Boot application project, refer to Spring Boot.
JavaFX
For more information about creating a JavaFX application, refer to Create a new JavaFX project.
Specify a name for your project.
Specify the path to the directory in which you want to create the project. By default, the IDE creates a directory with the same name as the project.
Create Git repository
Place the new project under version control.
You will be able to do it later at any time.
Select the language that you want to use in your application.
Select the build tool that will be used for managing dependencies, testing, packaging, automating the build process, and so on.
Specify the unique group identifier for your project. It should preferably start with the reversed domain name you control (for example, com.example ).
Specify a name for the artifact within the group, usually the project’s name.
From the JDK list, select the JDK that you want to use in your project.
If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory.
If you don’t have the necessary JDK on your computer, select Download JDK .
Select the libraries that you want to use in your application.
Quarkus
For more information about creating a Quarkus application, refer to Quarkus.
Specify the URL of the starter service that you want to use in your application. By default, the https://code.quarkus/io instance is specified, but you can use another custom service.
Specify a name for your project.
Specify the path to the directory in which you want to create the project. By default, the IDE creates a directory with the same name as the project.
Create Git repository
Place the new project under version control.
You will be able to do it later at any time.
Select the language that you want to use in your application.
Select the build tool that will be used for managing dependencies, testing, packaging, automating the build process, and so on.
Specify the unique group identifier for your project. It should preferably start with the reversed domain name you control (for example, com.example ).
Specify a name for the artifact within the group, usually the project’s name.
From the JDK list, select the JDK that you want to use in your project.
If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory.
If you don’t have the necessary JDK on your computer, select Download JDK .
Add sample code
Create a code sample together with the project.
Select extensions that you want to use in your project. If you select technologies that require additional plugins, the IDE will notify you about it once the project is created, and will suggest installing or enabling them.
Micronaut
For more information, refer to Micronaut.
Specify the URL of the starter service that you want to use in your application. By default, the https://micronaut.io/launch/ instance is specified, but you can use another custom service.
Specify a name for your project.
Specify the path to the directory in which you want to create the project. By default, the IDE creates a directory with the same name as the project.
Create Git repository
Place the new project under version control.
You will be able to do it later at any time.
Select the language that you want to use in your application.
Select the build tool that will be used for managing dependencies, testing, packaging, automating the build process, and so on.
Select a testing framework.
Specify the unique group identifier for your project. It should preferably start with the reversed domain name you control (for example, com.example ).
Specify a name for the artifact within the group, usually the project’s name.
Select an application type from the list.
From the JDK list, select the JDK that you want to use in your project.
If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory.
If you don’t have the necessary JDK on your computer, select Download JDK .
Select the Java version that the initializing service should use.
Select extensions that you want to use in your project. If you select technologies that require additional plugins, the IDE will notify you about it once the project is created, and will suggest installing or enabling them.
Настройка IntelliJ IDEA
Эта статья рассказывает о том, как настроить Ваше рабочее пространство IntelliJ IDEA для разработки плагинов со SpongeAPI и :doc: создавать системы, такие как Maven или Gradle `.
Gradle
Создание проекта
- Откройте IntelliJ IDEA.
- Нажмите Create New Project .
- Выберите Gradle в появившемся окне и нажмите кнопку Next .
- Введите Ваши Group ID, Artifact ID, и Version.
- Group ID обычно должен соответствовать названию Вашего пакета Java. Для подробностей смотрите Основной класс плагина .
- Artifact ID обычно должен соответствовать Вашему plugin ID, который задавался Вами ранее, например myplugin .
- Version — версия проекта, зависит только от Вас.
Редактирование build-скрипта
- Откройте build.gradle в навигаторе и добавьте зависимости.
- Отредактируйте build-скрипт, как описано в статье Настройка Gradle .
- Откройте Gradle tab в правой части окна программы и нажмите кнопку обновления (refresh).
- Установка Gradle завершена! Теперь Вы можете приступить к написанию кода Вашего плагина.
Импорт Вашего проекта
Если вы уже начали работу с вашим проектом и хотите снова импортировать его позже, вам необходимо его импортировать вместо повторного создания внутри вашей IDE:
- Нажмите File > Open
- Перейдите к файлу проекта build.gradle
- Нажмите Ok
Maven
Создание проекта
- Откройте IntelliJ IDEA.
- Нажмите Create New Project .
- Выберите Maven в появившемся окне и нажмите Next .
- Введите Ваши Group ID, Artifact ID, и Version.
- Group ID обычно должен соответствовать названию Вашего пакета Java. Для подробностей смотрите Основной класс плагина .
- Artifact ID обычно должен соответствовать Вашему plugin ID, который задавался Вами ранее, например myplugin .
- Version — версия проекта, зависит только от Вас.
Редактирование конфигурации проекта
- Откройте pom.xml в навигаторе.
- Отредактируйте build-скрипт, как описано в статье Настройка Maven .
- Обновите Ваш проект Maven.
- Импортируйте изменения Maven, если появилась подсказка.
Импорт Вашего проекта
Если вы уже начали работу с вашим проектом и хотите снова импортировать его позже, вам необходимо его импортировать вместо повторного создания внутри вашей IDE:
- Нажмите File > Open
- Перейдите к файлу проекта pom.xml
- Нажмите Ok
Git Интеграция
JetBrains предлагает документацию по интеграции Git:
Intellij idea как создать проект java
В прошлой теме мы рассмотрели, как создавать первую программу с последующим ее запуском в командной строке. Однако в реальности, как правило, крупные программы разрабатываются не при помощи простого текстового редактора, а с использованием таких средств как IDE или интегрированные среды разработки, которые упрощают и ускоряют написание кода и создание приложений. На данный момент одной из самых популярных сред разработки для Java является IntelliJ IDEA от компании JetBrains. Рассмотрим, как использовать данную среду.
Прежде всего загрузим установочный дистрибутив с официального сайта https://www.jetbrains.com/idea/download. По этому адресу можно найти пакеты для Windows, MacOS, Linux. Кроме того, сама среда доступна в двух версиях — Ultimate (платная с триальным бесплатным периодом) и Community (бесплатная). В данном случае выберем бесплатную версию Community .
Конечно, Community-версия не имеет ряда многих возможностей, которые доступны в Ultimate-версии (в частности, в Community недоступны опции для веб-приложений на Java). Но Community-версия тоже довольно функциональна и тоже позволяет делать довольно много, в том числе приложения на JavaFX и Android.
После установки запустим IntelliJ IDEA и создадим первый проект. Для этого на стартовом экране выберем New Project :
Далее откроется окно создания проекта. В левой части в качестве типа проекта выберем Java.
В поле Name укажем имя проекта. В моем случае проект будет называться HelloApp.
В поле Location можно указать путь к проекту, если не устраивает путь по умолчанию.
Поскольку мы будем работать с языком Java, в поле Language выберем пункт Java
Кроме того, в поле JDK можно указать путь к Java SDK, который будет использоваться в проекте. Как правило, это поле по умолчанию уже содержит путь к JDK, который установлен на локальном компьютере. Если это поле пусто, то его надо установить.
После этого нажмем на кнопку Create. После этого среда создаст и откроет проект.
В левой части мы можем увидеть структуру проекта. Все файлы с исходным кодом помещаются в папку src . По умолчанию эта папка пуста, никаких файлов кода у нас в проекте пока нет. Поэтому добавим файл с исходным кодом. Для этого нажмем на папку src правой кнопкой мыши и в контекстном меню выберем пункт New -> Java Class :
После этого нам откроется небольшое окошко, в которое надо ввести имя класса. Пусть класс будет называться Program :
После нажатия на клавишу Enter в папку src будет добавлен новый файл с классом java (в случае выше класс Program). А в центральной части откроется его содержимое — собственно исходный код:
Изменим код класса следующим образом:
public class Program < public static void main(String[] args) < System.out.println("Hello Java!"); >>
С помощью зеленой стрелки на панели инструментов или через меню Run -> Run. запустим проект.
И внизу IntelliJ IDEA отобразится окно вывода, где мы можем увидеть результат работы нашей программы.