所以我得到的错误是不能访问Window类型的封闭实例。必须使用Window类型的封闭实例(例如x.new A(),其中x是Window的实例)来限定分配。我想这是因为我试图实例化一个私有类,但如果我尝试使用它,我会得到一个不能在静态上下文中使用htis的错误。那么我该怎么做才能让风力发电机工作呢?
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");
}
}
}
问题是您试图在静态上下文中使用它,由于内部类本身不是静态的,因此它需要一个封闭类的实例才能存在,也就是说,它需要在该封闭实例上构造。这将导致一些有趣/丑陋的代码,如
MathWindowStateListener wsListener = mg.new MathWindowStateListener();
最好使私有内部类static
,这将解决您的问题,而不必求助于上面的笨拙。