I'm quite inexperienced in making GUI's with Swing and now I'm wondering if its possible to use "{" and "}" just to subdivide my code a little bit e.g.
[...]
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);
[...]
I tested it and I don't think it made any difference... Am I wrong?
Thanks in advance
Yes, it's possible, you can use a block anywhere you can use an individual statement. Variables declared within that block will only be valid within the block. E.g.:
void method() {
String allThisCodeCanSeeMe;
// ...
{
String onlyThisBlockCanSeeMe;
// ...
}
{
String onlyThisSecondBlockCanSeeMe;
// ...
}
// ....
}
But: Usually, if you find yourself wanting to do something like this, it suggests that you need to break the code into smaller functions/methods, and have what's currently your one method call those smaller parts:
void method() {
String thisMethodCanSeeMe;
// ...
this.aSmallerMethod(); // <== Can pass in `thisMethodCanSeeMe`
this.anotherSmallerMethod(); // <== if needed
// ...
}
private void aSmallerMethod() {
String onlyThisMethodCanSeeMe;
// ...
}
private void anotherSmallerMethod() {
String onlyThisSecondSmallerMethodCanSeeMe;
// ...
}
The only difference the braces make is that any variables declared within those braces are invisible outside of them.
For the example:
JPanel p = new JPanel();
{
JLabel a = new JLabel("Hello");
p.add(a);
int b = 5;
}
b = 10; // Compiler error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With