Hello,
my first post!
Can someone please explain to me the implications of declaring components inside the class constructor verses outside it?
For example, declaring the components outside the constructor seems to be common:
import javax.swing.*;
class mytest {
JLabel alabel;
JCheckBox acheckbox;
mytest() {
JFrame myf = new JFrame("Hello World");
myf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
alabel = new JLabel("Just some text");
acheckbox = new JCheckBox("Some random option");
myf.add(alabel); myf.add(acheckbox);
myf.setVisible(true);
}
// ... create frame etc...
but I've also seen the components created inside the constructor too:
import javax.swing.*;
class mytest {
mytest() {
JFrame myf = new JFrame("Hello World");
myf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel alabel = new JLabel("Just some text");
JCheckBox acheckbox = new JCheckBox("Some random option");
myf.add(alabel); myf.add(acheckbox);
myf.setVisible(true);
Now I'm guessing the reason is something to do with the scope of the component - ie making it accessible from another class (in another file), but thats just my guess. Can someone explain this to me please?
Thx
M