2016-02-26 116 views
0

我在方法(private void jButton2ActionPerformed)中创建了类DownloadManager的实例,并且需要通过另一种方法访问它?如何用不同的方法创建一个类的实例?

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { 
    //need to access the instance dman here 
}           

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {           
    DownloadManager dman = new DownloadManager(); 
    dman.actionAdd("http://dev.x-plane.com/download/tools/wed_mac_141r1.zip"); 
    dman.actionAdd("http://dev.x-plane.com/download/tools/wed_mac_141r1.zip"); 
    dman.setVisible(true); 
}  
+1

也许看看单身模式?可以使用一个类级别的实例? – MadProgrammer

+0

如果您需要其他方法中的DownloadManager对象,请在此处定义。我看到你不在jButton2ActionPerformed方法中使用它。 –

回答

1

“如果你希望能够从两个不同的方法,该方法的封闭范围内访问变量,定义变量。” -Sweeper

这基本上意味着你应该“拖”的方法之外的变量:

DownloadManager dman = new DownloadManager(); //Should put the variable here! 
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { 
    //need to access the instance dman here 
}           

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {           
    //DownloadManager dman = new DownloadManager(); I moved this line to above! 
    dman.actionAdd("http://dev.x-plane.com/download/tools/wed_mac_141r1.zip"); 
    dman.actionAdd("http://dev.x-plane.com/download/tools/wed_mac_141r1.zip"); 
    dman.setVisible(true); 
} 

这是非常简单的,不是吗?

或者,你可以得到下载管理器创建一个类:

public final class DownloadManagerUtility { 
    private DownloadManagerUtility() { // private constructor so that people don't accidentally instantiate this 

    } 

    private DownloadManager dman = new DownloadManager(); 
    public static void getDownloadManager() { return dman; } 
} 

这样做的好处是,你可以添加更多的被下载管理器在一个单独的类,它增加了可维护性相关的方法。

相关问题