我在方法(DownloadManager
)中创建了类private void jButton2ActionPerformed
的实例,需要在另一种方法中访问它吗?
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);
}
答案 0 :(得分: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; }
}
这样做的好处是,您可以在单独的类中添加与下载管理器相关的更多方法,从而提高可维护性。