BNetz
BNetz

Reputation: 361

Java/Swing: reference a component from another class

I have a Swing-GUI (built with Netbeans GUI-Builder), there is an label which I move around using the arrow-keys. Pressing the space-key another class is called. How can I access the label from this class and e.g. get the position?

Thanks in advance for help! Example-Code of the second class:

    public class Xy extends Thread {
      private Window s; // this is the jFrame-form
      public Xy(Window s) {
        this.s = s;
        s.setBackground(Color.yellow); // works
}


public void run() {
          // here i want to use the position of a label which is located on the form s
}

Upvotes: 2

Views: 4043

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

The best option is not to expose the JLabel if you don't absolutely need to do it. If you want the other class to change the label's position, then give the class that holds the label a method that allows outside classes to do this. If other classes need to query the label's position, then give the containing class public getter methods so that outside code can obtain the position data (not the label itself). This way, if you later decide that you don't want to use a JLabel but rather would like to display a different component altogether, you won't break code in other classes.

Or better still, base your GUI on a MVC model, and then change the logical label's position in the model. The view can listen for changes in the model via the observer pattern and then the view itself can change the label's position.

They key to all of this is use loose coupling whenever and wherever possible.

Upvotes: 2

NullPointer
NullPointer

Reputation: 53

There are two ways you can do this:

  1. Pass a reference to the JLabel to the class that needs it. For example, you could write a method that takes a JLabel as a parameter and then sets it to an instance variable.
  2. Make the JLabel a private instance variable in SomeClass and access it using a "getter" method (like getJLabel()).
  3. Make the JLabel a public instance variable in SomeClass (your JLabel/JFrame?) and access it using SomeClass.label.

The first would probably be considered better programming practice.

Upvotes: 1

Related Questions