• Post Reply Bookmark Topic Watch Topic
  • New Topic

What the heck!? JPanel background problem - weird!

 
Mike Lipay
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, so I got the background image working on my first window, then I went to add it to a second window and the weirdest thing happened. Two different applications (one called by the other), two different images (different names), but both windows display the same image. Here's the code:

First application:



Second application, which is called by the first one:



jeep02.jpg and jeep03.jpg are different pictures, but both windows show jeep02.jpg. Here is how the first app calls the second (in case it matters):
 
Francois Nadeau
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mike,

I noticed that both of your classes are called BackgroundPanel (I assume that they are in different packages). I am curious to see what happen if you make their names unique (to make sure that you are not creating the same object twice). Or I suppose you could make sure that each BackgroundPanel is constructed at least once with a debugger.

Hope this helps.
 
Mike Lipay
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That did it. I'm guessing that, although both panels were in different physical files java merges them at compile or execution time. Thanks!
 
Rob Spoor
Sheriff
Posts: 20820
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It probably imported the same BackgroundPanel class in both cases. You thought that you were using package2.BackgroundPanel but in fact you were using package1.BackgroundPanel. Since both classes are actually similar you didn't notice.

And that brings me to another issue. The classes are too similar to warrant two classes. Why not use one class with all the major code:
And if you want to shield the resource name from the calling class, subclass the panel:
As you see, you now only create such simple subclasses and leave the hard work to one single parent class.


Now, there is one more issue I have with this code. You use an int[] to store the size of the image. That leaves one potential danger (apart from it being null) - the size can be incorrect. I would use a java.awt.Dimension object instead:
Now you know that the object will always have space for the width and height, and it has easier ways to retrieve them as well - using the named fields instead of anonymous array indexes.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!