Reputation: 361
I have a Swing-GUI and an external class. In the constructor of the Swing GUI I instantiate a new object of the external class. But I can't use this object from other methods of the GUI-class (e.g. within an action listener). If I instantiate the object directly in the action listener then I can use all methods of the external class.
Here are the relevant snippets of code; if you need more tell me :-)
1) my External class
public class ExternalClass
{
private int a = 100;
public int getA() {
return a;
}
}
2) parts of my GUI-class
public class GUI extends javax.swing.JFrame {
// constructor
public GUI()
{
initComponents();
ExternalClass e = new ExternalClass();
}
//...
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
int u = e.getA();
// this doesn't work - the object e is not known by the method
}
//...
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new GUI().setVisible(true);
}
});
Upvotes: 0
Views: 673
Reputation: 2202
The object is declared in the constructor. Thus, it only exists within the constructor itself. If you want to use it in other methods you must declare it outside, as an attribute of the class, e.g. like this.
ExternalClass e;
// constructor
public GUI()
{
initComponents();
e = new ExternalClass();
}
Notice that this field will be visible to all the classes in the package that contains your GUI class. You might want to specify access level (private, public or none for package access).
Upvotes: 2
Reputation: 483
The scope of your e
object (scope means how visible a variable is) is confined to the constructor, because you said ExternalClass e
in that constructor.
The simplest solution would be to make this variable a member of the class - rather than just being defined in the constructor.
Move the declaration of ExternalClass e
outside the constructor, but still in the class itself. In your constructor, just do e = new ExternalClass();
. e
is visible in the constructor here because the constructor is a lower scope than the class itself, and it will be visible in the jButton1ActionPerformed
method too, for the same reason.
Upvotes: 2
Reputation: 32391
You declare and instantiate the e
variable inside the constructor, so it is visible inside the constructor only.
Declare it as a member variable and you can either instantiate it there or in the constructor.
Upvotes: 2