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);
}
});
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.
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).