【问题标题】:Implementing window listener in a separate frame class在单独的框架类中实现窗口侦听器
【发布时间】:2014-04-15 03:20:21
【问题描述】:

所以我得到的错误是没有 Window 类型的封闭实例是可访问的。必须使用 Window 类型的封闭实例来限定分配(例如 x.new A() 其中 x 是 Window 的实例)。 我认为这是因为我正在尝试实例化一个私有类,但是如果我尝试使用它,我会得到一个错误,即 htis 不能在静态上下文中使用。 那么我该怎么做才能让 hte windows wlistener 工作呢?

    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");
        }           
    }    
}

【问题讨论】:

标签: java swing windowlistener


【解决方案1】:

问题是你试图在静态上下文中使用它,并且由于内部类本身不是静态的,它需要一个封闭类的实例才能存在——即,它需要被构造在那个封闭的实例上。这将导致一些有趣/丑陋的代码,例如

MathWindowStateListener wsListener = mg.new MathWindowStateListener();

最好创建私有内部类static,这将解决您的问题,而无需诉诸上述问题。

【讨论】:

    猜你喜欢
    • 2014-05-11
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    相关资源
    最近更新 更多