Is there a way to prevent Eclipse from adding a new line before block opening brace ?

Eclipse format following code

p = new JPanel(new GridLayout(0, 1)); {
    p.add(login);
    p.add(password);
}
frame.add(p, BorderLayout.EAST);

to

p = new JPanel(new GridLayout(0, 1));
{
    p.add(login);
    p.add(password);
}
frame.add(p, BorderLayout.EAST);
有帮助吗?

解决方案

I also use this technique sometimes.

I think you will not be able to do this in Eclipse.

And I would say, this is good :)

Think, p = new JPanel(new GridLayout(0, 1)); is not a statement that controls the following block and thus it can not open it. When reading the code when we find } we intuitively expect for/if/etc in the start which is synonym to {. But there is just p = new ... It does not make any sense - the first thought would be, where is IF or something ! :)

We just want the block be separate from the outer block - textually or in vars visibility. So when scrolling up we found the starting { at the same indentation (no controlling or other statements before) - and that's it. No other thoughts, all good.

Just change the way you are thinking of it and you will enjoy { at the begging of line.

p.s. I use standard formatting so all other starting braces are at the end of line in my code.

其他提示

Go to Project->Properties->Java Coe Style->Formatter->Configure Workspace Settings->Edit->Braces

Change "Anonymous class declaration" to "same line"

I'm also a big fan of keeping my initialization code grouped in a block within the creation of my classes. So here's a little trick I use that takes advantage of static initializers:

p = new JPanel(new GridLayout(0, 1)) {{
    add(login);
    add(password);
}};
frame.add(p, BorderLayout.EAST);

As you can see, you can make calls to "add" without needing to prefix them with "p." as in: "p.add", and you no longer need to worry about Eclipse putting the braces at the beginning of the next line, since the semicolon is placed at the end of the whole block.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top