Eclipse Java code formatting

2019-08-06 11:49发布

问题:

I'm writting a GUI program.

It has several JPanels that conatin other components. It would be really nice if my code would look like this:

parent component code
    child component code
        grandchild component code

instead of this:

parent component code
child component code
grandchild component code

It would make the code far more readable. Is(Are) there some character(s) I can put in my code that Java will ignore, but Eclipse would detect it as a part of code that has to have additional indentation?

I know I can do all this manually, but I often set indentation automatically (ctrl+a, ctrl+i). That way I don't have to worry about indentation directly, I can make Eclipse manage it for me. However, that also nullifies any "custom" changes I made myself.

Adding {} does the trick, but it also influences on the way java reads the code, so that doesn't really work.

Maybe there are some plug-ins available for this? Something that would detect lines like e.g.

//{

and

//}

and then indent code that is enclosed in them?

回答1:

Select a block of text with the proper opening and closing braces, and then pressing Ctrl+Shift+F will format the selected block of text.

Morevoer, in eclipse you can go to Window -> Preferences -> Java -> Code Style -> Formatter. Here you can create a new formatter profile and assign a lot of your custom formatting rules.

Screenshot for easy reference