Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem Updating a JButton

 
Dan Griffin
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic