Hi,
I have a jFrame with a couple of jLabels, designed in Netbeans so most of the code is generated.

If I want to change the text of the label, I use .setText() inside my jFrame and it works great.
Now here's the problem. If I just make a String in a new class, I want this to appear on my jLabel.

I have the following code snippets:

GUI.java (jFrame):

public void setjLabel_answer(String jLabeltext) {
        jLabel_answer.setText(jLabeltext);
        System.out.println(jLabeltext);
    }

Spel.java:

GUI window = new GUI();
window.setjLabel_answer("hello world");

So I get the output "test" thanks to system.out.println, but the label doesn't change text?? :( When I use jLabel_answer.setText("test") inside my jFrame, it works great... I have a feeling this is maybe a downcast problem? It seems so simple, but I have no clue at the moment

If you call the newly created GUI object, do you expect the label to change for an existing GUI object?
You need a reference to the existing one to change its label.

@NormR1

hmmm just question in most complete GUI I always (maybe my endless lazyness) call

((PanelWhichHeltLabel) this.getParent().getParent()).changeLabelText();

because in All MultiThread App(not menaing only Java), is sometimes too hard timing output correctly to the GUI, this syntax (wrapped into invokeLater) always works, correctly and by expected order on the screen

why not this way

Depends on that layout. Components can be nested in different layers of Containers.
Perhaps instead of a hardcoded reach up thru the parents, use a loop and go up until you get to the layer you want.
Poor design to hardcode a dependency in your code.

Agree with Norm.
Best practice is to write a small public method in the GUI class that just takes the String as parameter and does whatever it needs to display it. That way other classes can call the method without needing any knowledge of the internals of the GUI class.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.