I have got a Java-Swing-GUI with a structure like this:
JFrame
— JPanel1
—–jButton1
—–jLabel1
My target is that when jButton1 is pressed I want to change the color of jLabel1 or set some text onto it, but this should be done in an external class (let’s call it externalClass).
So in the constructor of the GUI-class I pass itself to my external class:
public class GUIclass extends javax.swing.JFrame {
private externalClass e;
public GUIclass() {
initComponents();
e = new externalClass(GUIclass.this);
}
In my external class I am not able to access e.g. the label:
private GUIclass g;
public externalClass(GUIclass g) {
this.g = g;
System.out.println(g.getComponentCount());
// --> only 1, is this the JFrame (?)
System.out.println(g.getComponent(0).getName());
// always "null"
}
Could anybody please explain to me how I could get access to the label?
Also I am worried why the name of the component is always “null”.
Thanks in advance!
You make the instance of the JLabel global in your JPanel, and you provide a getter in the JPanel for your JLabel.
You pass the instance of the JPanel to your external class through the constructor.
Somewhere in your external class, you use the JPanel instance to get the JLabel instance.