This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes Problem Updating a JButton Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Problem Updating a JButton" Watch "Problem Updating a JButton" New topic

Problem Updating a JButton

Dan Griffin

Joined: Jul 22, 2009
Posts: 2
I need to update the background image of a JButton for my hangman program, when the button is firs created I can change th background image(ImageIcon) but after that Background image of the button will not update. I also tryed to change other properties of the button such as the size, but they would not change either. I tested the if statement by printing out text to make sure the program got to where it updates the button background and the text printed out. Is there any way to fix this problem of updating the button without linking the classes.

File with the problem:

Main File

File with the rest of the components:
pete stein

Joined: Feb 23, 2007
Posts: 1561
Your problem is that you are dealing with two completely different "man" objects, one called "panel" declared and initialized in your main class and displayed in your GUI, and the other called "a" declared initialized in the ButtonListener class and not displayed. It is the non-displayed "a" object that is having its hi(int count) method called, not the displayed "panel" object, and so calls to hi on the "a" object will have no effect on the display.

Solution: don't declare and initialize two man objects. Declare it once in the class, and pass it as a reference to your ButtonListener so that it can call methods on it.

Other suggestions:
1) Do not use a JButton for your hangman image but instead use a JLabel that holds ImageIcons. You really don't need or want a button's functionality here, but instead all you want to do is display an image reliably.
2) Use more accurately descriptive names for your variables, names whose meanings are immediately apparent on seeing them. For instance calling your man button "panel" or "a" won't help you understand this program when you look back at it a few weeks hence. Instead (again use a JLabel here) call it hangmanLabel or somesuch.

edit: a very simple example to demonstrate what I meant:

Best of luck.
Dan Griffin

Joined: Jul 22, 2009
Posts: 2
I agree. Here's the link:
subject: Problem Updating a JButton
Similar Threads
JAVA Compilation problem. Problem with importing code using the Get Method
Hangman problem!
Finishing touches to a Hangman game: kindly asking for ideas to help debug my logical errors
Hangman BufferReader ??
Updating the _ _ _ _ _ in a hangman game?