Reputation: 361
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
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
Reputation: 53
There are two ways you can do this:
The first would probably be considered better programming practice.
Upvotes: 1