BNetz
BNetz

Reputation: 361

Accessing Swing-Components from another class

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!

Upvotes: 2

Views: 5505

Answers (2)

Reimeus
Reimeus

Reputation: 159854

There is only one component attached directly to the JFrame namely the JRootPane.

To gain access to the JLabel from ExternalClass, you could get the component from the frame's content pane:

JPanel panel = (JPanel) g.getContentPane().getComponent(0);
JLabel label = (JLabel) panel.getComponent(1);

Also

g.getComponent(0).getName()

will return null by default as this is the name set to the JRootPane.

For more see How to Use Root Panes.

Upvotes: 3

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51565

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.

JLabel label = panel.getJLabel();

Upvotes: 3

Related Questions