我在使用Swing制作GUI时缺乏经验,现在我想知道是否可以使用"{"和"}"来细分我的代码,例如
[...]
JFrame f = new JFrame();
JPanel p = new JPanel();
{
JLabel a = new JLabel("Hello");
p.add(a);
JLabel b = new JLabel("World!");
p.add(b);
}
f.add(p);
[...]
Run Code Online (Sandbox Code Playgroud)
我测试了它,我觉得它没有任何区别......我错了吗?
提前致谢
T.J*_*der 18
是的,有可能,您可以在任何可以使用单独声明的地方使用块.在该块内声明的变量仅在块内有效.例如:
void method() {
String allThisCodeCanSeeMe;
// ...
{
String onlyThisBlockCanSeeMe;
// ...
}
{
String onlyThisSecondBlockCanSeeMe;
// ...
}
// ....
}
Run Code Online (Sandbox Code Playgroud)
但是:通常,如果你发现自己想要做这样的事情,它表明你需要将代码分解为更小的函数/方法,并且当前你的一个方法调用那些较小的部分:
void method() {
String thisMethodCanSeeMe;
// ...
this.aSmallerMethod(); // <== Can pass in `thisMethodCanSeeMe`
this.anotherSmallerMethod(); // <== if needed
// ...
}
private void aSmallerMethod() {
String onlyThisMethodCanSeeMe;
// ...
}
private void anotherSmallerMethod() {
String onlyThisSecondSmallerMethodCanSeeMe;
// ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
142 次 |
| 最近记录: |