0

I've recently started reading about Java Swing and lambda expressions. I read that you should always construct a frame by calling a method with java.awt.EventQueue.invokeLater() like this:

public class SwingTests
{
    private static void createGUI()
    {
        //creates frame, packs etc.
    }

    public static void main(String[] args)
    {
        java.awt.EventQueue.invokeLater(new Runnable()
            {
                public void run()
                {
                    createGUI();
                }
            }); //haven't really figured out formatting for this yet
    }
}

Then my IDE suggested using a lambda expression instead of the anonymous class, so I switched to

java.awt.EventQueue.invokeLater(() -> createGUI());

but while reading, I also discovered method references and wanted to use those. However, replacing () -> createGUI()with this::createGUI gives a compiler error because "non-static variable this cannot be referenced from a static context". I discovered that SwingTests::createGUI works, but referring to a class by name in its own body seems weird. Is there a better way for this?

Kalobi
  • 81
  • 1
  • 6
  • 1
    It's a static method reference, that's how you call it... – OneCricketeer Aug 10 '16 at 13:57
  • 7
    `SwingTests::createGUI` is not weird and that's the normal way to refer to a static method. – Jesper Aug 10 '16 at 13:58
  • 1
    `this` refers to a concrete instance of a class, i.e. it is not static. Any static elements like methods or fields are in the scope of the class they belong to so referring to that method via the class name is the correct way (you don't have any instance to determine which method is meant to it has to be qualified with the class name). – Thomas Aug 10 '16 at 13:58
  • See also [“Why class/object name must be explicitly specified for method references?”](http://stackoverflow.com/q/30251867/2711488) – Holger Aug 17 '16 at 13:50

1 Answers1

0

Apparently, this is the proper way, and any shortcuts that could have been allowed would cause ambiguity for the compiler. See also Holger's link:

See also “Why class/object name must be explicitly specified for method references?”

Community
  • 1
  • 1
Kalobi
  • 81
  • 1
  • 6