1

I have a JPanel, and i want to add an image as its background. How can i do that ?

frame = new JFrame("Some frame");
panel1 = new JPanel();
panel1.setBorder(new EmptyBorder(5, 5, 5, 5));
// NEED TO ADD AN IMAGE TO THIS PANEL

panel1.setLayout(cardlayout);
frame.getContentPane().add(panel1);

frame.setLocationByPlatform(true);
frame.setVisible(true);

I need to add an image to the panel and how can i do it ?

UPDATE 1

    panel1 = new JPanel()
    {
    private static final long serialVersionUID = 1L;

    @Override
    public void paintComponent(Graphics g)
    {

        g.drawImage(Toolkit.getDefaultToolkit().createImage("1.jpg"), 0, 0, null);
    }
};
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Sharon Watinsan
  • 9,620
  • 31
  • 96
  • 140
  • In the update I see you are forgetting to call `super.paintComponent(g);` in overridden `paintComponent` method, this could be a major problem (even the problem besides extracting image in `paintComponent`). overriden methods should optimally first call their `super` – David Kroukamp Dec 09 '12 at 21:56
  • see these answers [here](http://stackoverflow.com/questions/13237908/loading-image-in-java-code-from-c-drive/13238468#13238468) or [this one](http://stackoverflow.com/questions/12660122/image-resizing-and-displaying-in-a-jpanel-or-a-jlabel-without-loss-of-quality/12660146#12660146) for some examples – David Kroukamp Dec 09 '12 at 22:00
  • @DavidKroukamp i tried adding `super.paintComponent(g);` but it still doesn't add an image to Jpanel – Sharon Watinsan Dec 09 '12 at 22:01
  • is 1.jpg located in the same directory as your jar? or is it bundled? – David Kroukamp Dec 09 '12 at 22:04
  • Yes, just below the file that contains the GUI. In the same package – Sharon Watinsan Dec 09 '12 at 22:05
  • 1
    if it is contained within the jar and the same package as the executing class try: `Image img = ImageIO.read(getClass().getResourceAsStream("1.jpg"));` otherwise you'd have to do "/packagename/1.jpg" (note any period (`.`) within *packagename* must be replaced by /) – David Kroukamp Dec 09 '12 at 22:07
  • Do not try to load the image inside the `paintComponent(..)` method! 1) Load them when the component is constructed. 2) When drawing the image, use the image observer (the panel is an image observer). – Andrew Thompson Dec 10 '12 at 01:59

2 Answers2

4

You need to override the method paintComponent(Graphics g) of JPanel and use drawImage() on the Graphics object g as in this example.


Also, check these two examples by @trashgod:

  1. example.
  2. example.
Community
  • 1
  • 1
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • Also, I'd use `ImageIO` for the loading of the images – MadProgrammer Dec 09 '12 at 22:15
  • @sharonHwk `Toolkit.getDefaultToolkit().createImage("1.jpg")` may return a `null` result or empty image if the image you are trying to reference does not exist. Make sure that the image exists and can be referenced from the context of your application – MadProgrammer Dec 09 '12 at 22:17
  • 1
    @MadProgrammer *"`createImage("1.jpg")` may return a `null` result"* That is why I prefer `ImageIO.read(..)` - when broken it supplies much more useful information. :) – Andrew Thompson Dec 10 '12 at 01:35
  • @AndrewThompson No argument here – MadProgrammer Dec 10 '12 at 01:40
3

You have a resource location problem.

Toolkit#createImage may return an empty image if the resource can not be found.

I suggest you use the ImageIO API instead, it supports a wider range of image formats, but will also throw an exception if the image is not found or can not be loaded.

How you load the image will also depend on where the image is.

If the image exists on the file system, you can simply use a File object reference, if the image is an embedded resource (within you application), you will need to use Class#getResource to obtain a URL to it.

enter image description here

public class TestGraphics {

    public static void main(String[] args) {
        new TestGraphics();
    }

    public TestGraphics() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(new PaintTest());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class PaintTest extends JPanel {

        private BufferedImage image;

        public PaintTest() {

            setLayout(new BorderLayout());
            try {
                // Use this if the image exists within the file system
                image = ImageIO.read(new File("/path/to/image/imageName.png"));
                // Use this if the image is an embedded resource
//                image = ImageIO.read(getClass().getResource("/path/to/resource/imageName.png"));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public Dimension getPreferredSize() {
            return image == null ? super.getPreferredSize() : new Dimension (image.getWidth(), image.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (image != null) {
                int x = (getWidth() - image.getWidth()) / 2;
                int y = (getHeight()- image.getHeight()) / 2;
                g.drawImage(image, x, y, this);
            }
        }

    }

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • +1 nice advices and example. I always use `ImageIO#read` but never would have thought `Toolkit#createImage` would be any different, nice to know. – David Kroukamp Dec 09 '12 at 23:33