【问题标题】:Access a class object from its inner class从内部类访问类对象
【发布时间】:2011-01-26 09:48:07
【问题描述】:

此方法在 JFrame 对象内部,我如何将该 JFrame 对象作为参数传递给其内部类中的方法? 我的代码是: 评论解释了我有兴趣做的事情:

公共无效运行时间(){
        ActionListener action = new ActionListener(){
            公共无效actionPerformed(ActionEvent e){
                计数++;
                text.setText(new Integer(count).toString());
                而(计数==2012){
                    //我想传递持有这个而不是null的框架,怎么可能?
                    JOptionPane.showMessageDialog(null, "HelloEnd", "End of World", JOptionPane.INFORMATION_MESSAGE, new ImageIcon("explode.jpg"));
                    休息;
                }
            }
        };
        tr = new Timer(1000,action);
        tr.start();
    }

【问题讨论】:

标签: java class inheritance


【解决方案1】:

希望这个问题不是answered before。还是试试吧

 JOptionPane.showMessageDialog(JFrame.this, "HelloEnd", "End of World", JOptionPane.INFORMATION_MESSAGE, new ImageIcon("explode.jpg"));

【讨论】:

    【解决方案2】:

    您可以使用OuterClassName.this

    【讨论】:

    • 其实我之前也遇到过这个问题。问题的上下文是相同的,我必须从内部类访问对封闭类的引用。谢谢你的回答。太好了,解决了我的问题。
    【解决方案3】:

    AFAIK,如果您的方法不是静态的,您可以使用 thissuper 关键字。这是一些tutorial。例如:

    JOptionPane.showMessageDialog(this, "HelloEnd", "End of World", JOptionPane.INFORMATION_MESSAGE, new ImageIcon("explode.jpg"));
    

    【讨论】:

    • 如果我使用 this 关键字,那么 this 代表我的代码中的动作对象(来自 ActionListener 类),但我想从外部类中制作父组件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 2021-08-18
    • 2017-11-13
    相关资源
    最近更新 更多