我正在使用Swing应用程序。
public class Owner extends JPanel{
Child child=null;
public Owner(){
child=new Child();
}
}
public class Child extends JPanel{
public Child(){
// Here I want the instance of Owner class.
// This child class is being created from many classes(almost 1000) like the Owner class.
}
}
我想要一些方法来获取调用类实例的实例,也许使用反射。
这样我就可以将KeyListener
与每个实例相关联。
这是必需的,否则我必须在所有1000个类中编写相同的代码。
我的所有类都在扩展JPanel
,一旦组件与组件关联到父组,我就可以从Parent
属性中获取父级。但是我在Child
的构造函数中需要它,即组件尚未与Owner
相关联。
答案 0 :(得分:1)
public class Owner extends JPanel{
Child child=null;
public Owner(){
child=new Child(this);
}
}
public class Child extends JPanel{
Object owner ;
public Child(Object owner ){
this.owner = owner ;
// Here I want the instance of Owner class.
// This child class is being created from many classes(almost 1000) like the Owner class.
}
}
答案 1 :(得分:0)
这样的事可能会对你有所帮助:
public class Owner extends JPanel {
Child child;
public Owner() {
child = new Child(this);
}
}
public class Child extends JPanel {
Owner owner;
public Child(Owner owner) {
this.owner = owner;
// add key listeners here to owner
owner.addKeyListener(...)
}
}