-1

I tried a simple program to add an image on the background of a frame using java swing. But whenever I resize the frame the background image size remains the same. That means If I shorten my frame, the image is cut, only a little portion of the image is seen. If I enlarge the frame then the new portion of my frame takes default white color. How can I solve it?

ImageIcon img= new ImageIcon("gari.png");
JLabel back_img= new JLabel(img);
background frem = new background();`your text`
frem.getContentPane().add(back_img);
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • A JLabel does not try to resize the image. Instead, it requests the LayoutManager to size it so it can hold the (unscaled) image. You will have a hard time telling a JLabel to behave otherwise. – Queeg May 26 '23 at 22:11
  • For [example](https://stackoverflow.com/questions/12876615/how-do-i-resize-images-inside-an-application-when-the-application-window-is-resi/12876799#12876799) – MadProgrammer May 27 '23 at 00:11
  • aside: stick to java naming conventions – kleopatra May 27 '23 at 08:15
  • Check out the [Background Panel](https://tips4java.wordpress.com/2008/10/12/background-panel/) for a simple example of how to do this as well as a class that supports more complex painting. – camickr May 27 '23 at 13:54

1 Answers1

0

If it were me, rather than adding a JLabel to the ContentPane, I would make a custom JPanel that paints the background image using the Graphics.paintImage option that allows you to scale the image size. Then I'd set this JPanel as the content pane.

Another option you might want to explore is using java.awt.Paint and https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/ui/swing_ex/JPanelCustomBkground.java

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80