Domanda

So the error I get is No enclosing instance of type Window is accessible. Must qualify the allocation with an enclosing instance of type Window (e.g. x.new A() where x is an instance of Window). I think it's because i'm trying to instantiate a private class, but if I try and use this, I get an eror that htis cannot be used in a static context. So what I do to get hte windo wlistener working?

    public class Window {
    static MathGame mg;

    private static void createAndShowGUI()  {
        JFrame frame = new JFrame("Epsilon");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mg = new MathGame();
        frame.getContentPane().add(mg);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

    //error here: No enclosing instance of type Window is accessible. 
    //Must qualify the allocation with an enclosing instance of type Window
     (e.g. x.new A() where x is an instance of Window).

        MathWindowStateListener wsListener = new MathWindowStateListener();

        frame.addWindowStateListener(new MathWindowStateListener());
    }

    /**
     * @param args
     */
    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable()   {
            public void run()   {
                createAndShowGUI();
            }
        });

    }

    private class MathWindowStateListener implements WindowStateListener{

        @Override
        public void windowStateChanged(WindowEvent we) {
            if(we.equals(WindowEvent.WINDOW_CLOSED))
            {
                System.out.println("window closed");
                mg.sql.removeUser();
            }
            else if(we.equals(WindowEvent.WINDOW_CLOSING))
                System.out.println("window closing");
        }           
    }    
}
È stato utile?

Soluzione

The issue is that you're trying to use it in a static context, and since the inner class is not static itself, it needs an instance of the enclosing class for it to exist -- i.e., it needs to be constructed on that enclosing instance. This will lead to some funny/ugly code such as

MathWindowStateListener wsListener = mg.new MathWindowStateListener();

Better to make the private inner class static and this will solve your problem without resorting to the above kludge.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top