3

I'm making a Java Applet that has a null layout. I know everyone says this is bad, but in this case it is needed. I'm trying to add a background image to my applet, and I'm not too sure how to do it. I've seen lots of different ways but I don't really understand any; I'm new to programming.

This is what I tried...

 JLabel background=new JLabel(new ImageIcon("Backgrounds\background.png"));
 background.setBounds(0, 0, 850, 500);
 add(background);

and nothing appeared. The image is called background.png and is located in my project folder, within a folder called Backgrounds. Any ideas why this isn't working or how to get it working?

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
JL9
  • 533
  • 3
  • 17
  • 2
    Why is it needed? See also the examples cited [here](http://stackoverflow.com/tags/embedded-resource/info). – trashgod Apr 14 '15 at 21:00
  • It's just a background for my applet to make it look good – JL9 Apr 14 '15 at 21:01
  • 5
    Create a custom component extending from JPanel, override its paintComponent method and paint your image within it. Set this panel as the applets content pane and set the applets layout – MadProgrammer Apr 14 '15 at 21:06
  • 2
    *"new ImageIcon("Backgrounds\background.png")"* <- This is trying to load the image from the file system of the client computer, which is security violation. Better to package the image in the jar and load the image through ImageIO and Class#getReaource – MadProgrammer Apr 14 '15 at 21:08
  • 1
    Background image [example](http://stackoverflow.com/questions/24176008/background-image-for-a-jpanel-not-working/24176183#24176183) – MadProgrammer Apr 14 '15 at 21:10
  • 1
    Why code an applet? If it is due to the teacher specifying it, please refer them to [Why CS teachers should **stop** teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). – Andrew Thompson Apr 14 '15 at 21:11
  • Also consider a [hybrid](http://stackoverflow.com/q/12449889/230513). – trashgod Apr 14 '15 at 21:14
  • Just tried... 'BufferedImage bg = ImageIO.read(Menu.class.getResource("/imgs/rotom.jpg")); JLabel label = new JLabel(new ImageIcon(bg)); setContentPane(label);', it didn't do anything? @MadProgrammer – JL9 Apr 14 '15 at 21:28
  • It's going to be impossible to diagnose without know how you files are structured and if the files are packaged into your jar – MadProgrammer Apr 14 '15 at 21:46

0 Answers0