从参数对象获取对实例化对象的引用

时间:2013-11-27 22:29:37

标签: java containers jcomponent

我实例化两个依赖类:

//Create and set up the content pane.
ImportTablePanel surveyTablePanel = new ImportTablePanel(genErrorDescArray); 

SurveyTree surveyTreePanel = new SurveyTree(surveyTablePanel,genErrorDescArray); 

SurveyTree类有一个方法 setImportOK(),我想从ImportTablePanel类访问它。

public class SurveyTree extends JPanel 
                      implements TreeSelectionListener  {

...

public void setImportOK(){
// my code here
}

我遇到的问题是SurveyTree对象的实例化将ImportTablePanel作为参数。这使得很难获得对SurveyTree对象的引用。

经过多次尝试,我终于通过从表容器向上导航来设法使其工作 - 请参阅下面的代码。 我确信有一个更好的方法来获取容器参考 - 理想情况下像table.getContainer(int indexFromTop) 可以有人提出建议吗?

public class ImportTablePanel extends JPanel implements TableModelListener {

...

 SurveyTree  surveyTree = (SurveyTree) table.getParent().getParent().getParent().getParent().getParent().getParent().getParent().getParent();
 surveyTree.setImportOK();

}

非常感谢..

最后我使用了单身设计模式。

public class SwingUtility {

private static SwingUtility instance;
private static SurveyTree surveyTreePanel;

SwingUtility() {

}

public static synchronized SwingUtility getInstance(){
    if (instance == null){
        instance = new SwingUtility();
    }
    return instance;
}

public SurveyTree getSurveyTreePanel() {
    return surveyTreePanel;
}

public void setSurveyTreePanel(SurveyTree surveyTreePanel) {
    SwingUtility.surveyTreePanel = surveyTreePanel;
}

}

使用main方法

创建单例实例
// set up singleton instance of survey form
    SwingUtility swingUtility = new SwingUtility();
    swingUtility.setSurveyTreePanel(surveyTreePanel);

然后从导入表面板

引用SurveyTree
 SurveyTree surveyForm =   SwingUtility.getInstance().getSurveyTreePanel();
 surveyForm.setImportOK();

0 个答案:

没有答案