0

Hello everyone i have this Image that i want it to appear as my background and my other information to be on top of it i want it to fill the entire JApplet, can anyone give me the method... please.

I dont know if i should include a JPanel panel = new JPanel();

the add the background? am new in Java help me.

backGround = getImage(getCodeBase(), "download.jpg");
        BackGroundPanel background = new BackGroundPanel();
        background.setLayout(new FlowLayout());
        background.setBackGroundImage(backGround);

I have imported my jpg to my src java but cant load.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
KIM
  • 47
  • 1
  • 8
  • Also take a look at [Reading/Loading an Image](http://docs.oracle.com/javase/tutorial/2d/images/loadimage.html) – MadProgrammer May 04 '15 at 16:36
  • Why is it marked duplicate? I tried those solutions and couldnt work? :( – KIM May 04 '15 at 16:40
  • It's the same process, create a custom component, extending from `JPanel`, override it's `paintComponent` method and paint your image within it. Apply this component as the `JApplet`'s `contentPane` and initialise the UI as you normally would. The fact that you're using applet doesn't actually change how it's done. I suspect that you're not loading the image correctly, hence the reason I also added the link to [Reading/Loading an Image](http://docs.oracle.com/javase/tutorial/2d/images/loadimage.html), as you state the image is your `src` directory, which means it you can't use `getImage` – MadProgrammer May 04 '15 at 16:43
  • hey @MadProgrammer forgive me for asking but where is this location? getCodeBase(), and can i save my picture there? am reading the link too. I have been learning Java on my own – KIM May 04 '15 at 16:49
  • Try using ImageIO.read(getClass().getResource("/path/to/image/download.jpg")). With the images stored in the src directory, the image is like embedded in the resulting jar and not stored on the server – MadProgrammer May 04 '15 at 21:10

1 Answers1

0

Here's a quick testapplet I wrote to test this, and it seems to work (should work with any Java version as well). It draws the background, and places a label (so any Component) on top of it.

Code:

import java.applet.Applet;
import java.awt.*;
import java.net.*;
public class BGTest extends Applet
{
    Label testLabel;
    Image bgImage = null; 

    public void init()
    {
        try 
        { 
            MediaTracker tracker = new MediaTracker (this);
            bgImage = getImage
            (new URL("download.jpg")); 
            tracker.addImage(bgImage, 0);
        } catch (Exception e) { System.out.println(e.toString());}      
        testLabel=new Label("Testing");
        add(testLabel);     
    }

    public void paint(Graphics g) 
    {   
        super.paint(g);
        g.drawImage(bgImage,0,0,this); 
    }
}
MChaker
  • 2,610
  • 2
  • 22
  • 38