Beautify / Format Java code in Visual Studio Code

I have tried some proposals on here and here, but none of them works. How do you accomplish it for Java code or is there a way for general? En passant, I've install XML formatter in order that it may work, but not.

enter image description here enter image description here

Upvotes: 30

Views: 94325

Answers (3)

keemahs
keemahs

Reputation: 998

I feel it's a good idea to store a configuration with each project (and not globally).

  1. open workspace settings json file. Following steps work on my laptop -
    1. press F1
    2. select Preferences: Open Workspace Settings (JSON)
  2. paste the below there -
{
  "java.format.settings.url": "./eclipse-java-google-style.xml"
}
  1. Now you can create a file in the root folder eclipse-java-google-style.xml which has the settings.
  2. There, you can paste the contents of eclipse-java-google-style.xml. Optionally set org.eclipse.jdt.core.formatter.join_wrapped_lines to false.

Upvotes: 4

RICHARD ABRAHAM
RICHARD ABRAHAM

Reputation: 2528

Formatting a JAVA Document in VSCode requires one to follow the below steps:

  1. Install the plugin: Language Support for Java(TM) by Red Hat from the Extensions window in VSCode.

    • You can open the Extensions window from the left aligned sidebar or simply by pressing Ctrl + Shift + X
  2. Post Installation, from the required page with JAVA code

    • Right Click and choose Format Document With..
    • In the command pallette that opens up on top, select Language Support for Java(TM) by Red Hat option

The Java Document should be now properly formatted.

PS: Trying Alt+Shift+F may not work for users who have set their default formatter as Prettier - Code formatter or alike. By default, java formatting is not supported by it.
If Language Support for Java(TM) by Red Hat is the only formatter plugin installed, then Alt+Shift+F might work for you.

If you wish to bind Alt+Shift+F to format your JAVA Document,
then you can add the below configuration to your settings.json by:

  1. Pressing Ctrl+, to open your Settings
  2. From Top Right Corner, select Open Settings(JSON) either for User or Workspace settings.
  3. Append the below JSON property to it and save:
    "[java]": {
        "editor.defaultFormatter": "redhat.java",
      },

Upvotes: 40

Matt Bierner
Matt Bierner

Reputation: 65195

For proper formatting, you need to install a VSCode extension that provides Java formatting. Try this one from Redhat: https://marketplace.visualstudio.com/items?itemName=redhat.java

After the extension is installed, that standard code format commands / shotcuts should work for Java code.

Upvotes: 8

Related Questions