Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Changing text of JLabel by pressing a button?

 
Marko Matosevic
Greenhorn
Posts: 12
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I feel really dumb by asking this, but I don't get what I missed in the code. I used the example of changing the text of a button by clicking on it, but instead I also added a JLabel and tried to make the button change its text instead, but it didn't work. What did I do wrong?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Marko. Welcome to the Ranch!

The problem is this line:
What that looks like you wanted to do is initialise the label variable declared on line 6. This is what you try to change the text of on line 29.

But it doesn't. It declares a new, local variable and initialises that instead. Which means that line 29 is acting on the wrong JLabel. In fact, since you never initialise that variable at all, I would expect line 29 to throw a NullPointerException.

You're also doing something similar with the button variable on line 16.
 
Marko Matosevic
Greenhorn
Posts: 12
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I knew it was something stupid like that. I just had to alter those two lines and it worked.



Thanks!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!