ewok
ewok

Reputation: 21443

permanent background image on a JPanel

I am building a swing interface for drawing overlays over a particular image. I have found several examples of how to draw an image on a JPanel, and I am able to do this without difficulty. However, I would like to keep this image completely static while dynamically drawing overlays on top of it. With that in mind, it would be better if I could set the image as a permanent background of the panel, rather than having paintComponent() redraw the image every time. This would be particularly useful, as there will frequently be situations where I want to removeAll() graphics currently on the panel and redraw new ones.

So my question is this: is there a way to set a permanent background image in JPanel, or do I have to redraw the image every time paintComponent() is called?

Upvotes: 0

Views: 572

Answers (2)

user890904
user890904

Reputation:

maybe you can try putting the Jpanel inside another Jpanel. You draw the image on the container JPanel. then make your inner JPanel a transparent one. this way, when there are no objects on it, you see the background of the parent JPanel which did not change.

Upvotes: 1

mKorbel
mKorbel

Reputation: 109815

  • put Image as Icon / ImageIcon to the JLabel

  • use this JLabel instread of JPanel

  • JLabel hasn't implemented any LayoutManager in compare with JFrame(BorderLayout) or JPanel(FlowLayout)

  • you have to define the proper LayoutManager, that accepting PreferredSize came its child(s)

  • then there are accesible (almost nearly) all methods as for JPanel, as container works

Upvotes: 2

Related Questions