954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

jPanel setText from other class

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

JSS540
Newbie Poster
1 post since May 2011
Reputation Points: 10
Solved Threads: 0
 

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
Posting Expert
Moderator
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
 

@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

mKorbel
Veteran Poster
1,141 posts since Feb 2011
Reputation Points: 480
Solved Threads: 224
 

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.

NormR1
Posting Expert
Moderator
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
 

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.

JamesCherrill
Posting Genius
Moderator
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: