内部类里如何获得外部类的引用??
如在gui,将监听类作为内部类,在这个监听类中需要获得外部类的引用,如在这个监听类的方法中弹出一对话框,在该对话框中需要指明其你框架,此时如何获得这个你框架???
public class RegisterNewUserJFrame extends JInternalFrame
{
.....
class SexActionListiner implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
userSexStr=e.getActionCommand(); JOptionPane.showMessageDialog(???,userSexStr);
}
}
.....
}
〉在RegisterNewUserJFrame内定义
〉RegisterNewUserJFrame mySelf = this;
〉这样内部类可以取道mySelf了
那不跟RegisterNewUserJFrame.this一样吗?
我觉得RegisterNewUserJFrame.this应该就是楼主所说的,不过好像是其他的原因造成的NullPointerException
to littlecong(虫子) :
没错,我用这种方法就可以了,但老觉得有点怪怪的。所以提了这个问题。
to farawayzheng_necas(遥远) :
不对吧,此时就是RegisterNewUserJFrame.this为空。
to huangzt():
RegisterNewUserJFrame.this.getTopLevelAncestor()也不对。
没有很明白你为什么要这么做!
一个建议仅供参考:
1、在内部类SexActionListiner 中声明变量:RegisterNewUserJFrame mySelf 。
2、然后在外部类中调用addActionListener(new SexActionListiner(this) )时,将外部类的句柄this作为参数传给内部类。
3、在内部类的construct中实例化 myself