Reputation: 1
I have created an instance of the class DownloadManager
in a method (private void jButton2ActionPerformed
) and need to access it in another method?
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);
}
Upvotes: 0
Views: 39
Reputation: 272370
"If you want to be able to access a variable from two different methods, define the variable in the enclosing scope of the method." -Sweeper
Which basically means you should "drag" the variable outside of the methods:
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);
}
That's very simple isn't it?
Alternatively, you can create a class for getting the download manager:
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; }
}
The advantage of this is that you can add more methods that are related to download manager in a separate class, which increases maintainability.
Upvotes: 1