110
votes

I have a Java project in IntelliJ to which I just added a bunch of files in a nested folder hierarchy. Many of these files are tests and include the main method, so I should be able to run them. However I cannot figure out how to do this.

I'm new to IntelliJ and previously files have shown up in the project hierarchy with the symbol that corresponds to "Java class that contains declaration of the main() method." but in this scenario they show up with the symbol corresponding to "Java class located out of the source root."

So how do I compile and run these files?

4
For anybody coming here with the same issue but no "source root" problem - the runnability and "main class" indicators disappeared when I accidentally imported com.sun.org.apache.xpath.internal.operations.String - still can't figure out why it happened! (IDEA 2018.1, JDK 8, Maven)Janaka Bandara

4 Answers

68
votes

The documentation you linked actually has the answer in the link associated with the "Java class located out of the source root." Configure your source and test roots and it should work.

https://www.jetbrains.com/idea/webhelp/configuring-content-roots.html

Since you stated that these are tests you should probably go with them marked as Test Source Root instead of Source Root.

148
votes

Select the folder containing the package tree of these classes, right-click and choose "Mark Directory as -> Source Root"

8
votes

Here is the complete procedure for IDEA IntelliJ 2019.3:

  1. File > Project Structure

  2. Under Project Settings > Modules

  3. Under 'Sources' tab, right-click on 'src' folder and select 'Sources'.

  4. Apply changes.

2
votes

Sometimes under the current automatically configured sources root you need to specify the module classpath:

  1. Click Run -> Edit Configurations
  2. Select the project you can't find the main class for
  3. Under the Use classpath of module pulldown see if there is a sub directory that has your main class under it. If so, select it.
  4. try to configure the main class again.