I've been poking through the auto-generated code when making a new JFrame project with NetBeans, and came across this in my main
method:
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TestClass().setVisible(true);
}
});
After some reading I've come to understand the need for invokeLater so the GUI components are handled in the EDT. That said, the line new TestClass().setVisible(true);
, as it's implemented here, is a bit boggling to me. I get it in the context of creating a new instance...
TestClass tclass = new TestClass();
tclass.setVisible(true);
...but I don't quite follow what's going on in the run()
method above. Is that code creating an anonymous class? I've run across that term but don't fully understand it yet. I assume it's not creating an instance in the "textbook" way I listed above because there's no variable (that I can see anyway) to refer back to that instance.
As an aside, it seems to me having your main
method inside a JFrame class (or any GUI class, for that matter) isn't ideal anyway, so I'll probably move it.
new TestClass().setVisible(true)
is just creating a new instance, invoking setVisible(true)
on it and then "forgetting" that instance by not saving a reference to it. It is actually equivalent to
TestClass tclass = new TestClass();
tclass.setVisible(true);
because the variable tClass
is not accessible outside the run method and the run method does nothing but invoking setVisible
on it.
If two or more (void) methods on the instance had to be called, you would need to use a variable to hold a reference to the instance, and you couldn't do the "one-line" trick that puzzeled you:
TestClass tclass = new TestClass();
tclass.setVisible(true);
tclass.methodX();
It is not an anynymous class (see https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html) , it is something like an 'anonymous instance' although I don't think that term exists.
Depending on your project layout, it might make sense to move the main
method to a separate class.