Search code examples
javaswinggraphicsjframebufferedimage

How to add background image using Graphics in Java


private void render() {
    BufferStrategy bufferStrat = this.getBufferStrategy();
    
    if(bufferStrat == null) {
        createBufferStrategy(3);
        return;
    }
     
    Graphics g = bufferStrat.getDrawGraphics();
    
    g.drawImage(image, 0,0, getWidth(), getHeight(), this);
    
    g.dispose();
    bufferStrat.show();
}

This gives a black background (which is right technically).

So how would I add a background image from my windows computer to replace the black background in my JFrame?


Solution

  • Simple example based on the example in the BufferStrategy JavaDocs

    Background

    import java.awt.Canvas;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.image.BufferStrategy;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    
    public class Test {
    
        public static void main(String[] args) {
            new Test();
        }
    
        public Test() {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    JFrame frame = new JFrame();
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setVisible(true);
                }
            });
        }
    
        public class TestPane extends Canvas {
    
            private volatile boolean keepRendering = true;
            private BufferedImage background;
            private Thread renderThread;
    
            public TestPane() {
                try {
                    background = ImageIO.read(getClass().getResource("/images/Background.jpg"));
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
    
            @Override
            public Dimension getPreferredSize() {
                if (background == null) {
                    return new Dimension(200, 200);
                }
                return new Dimension(background.getWidth(), background.getHeight());
            }
    
            @Override
            public void addNotify() {
                super.addNotify();
                if (renderThread != null) {
                    keepRendering = false;
                    try {
                        renderThread.join();
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
    
                keepRendering = true;
                renderThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        render();
                        try {
                            Thread.sleep(16);
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                    }
                });
                renderThread.start();
            }
    
            @Override
            public void removeNotify() {
                super.removeNotify();
                if (renderThread == null) {
                    return;
                }
                keepRendering = false;
                try {
                    renderThread.join();
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
    
            protected void render() {
                BufferStrategy strategy = getBufferStrategy();
                if (strategy == null) {
                    createBufferStrategy(2);
                }
                // Just in case
                strategy = getBufferStrategy();
                if (strategy == null) {
                    return;
                }
                while (keepRendering) {
    
                    // Prepare for rendering the next frame
                    // ...
                    // Render single frame
                    do {
                        // The following loop ensures that the contents of the drawing buffer
                        // are consistent in case the underlying surface was recreated
                        do {
                            // Get a new graphics context every time through the loop
                            // to make sure the strategy is validated
                            Graphics graphics = strategy.getDrawGraphics();
    
                            if (background != null) {
                                int x = (getWidth() - background.getWidth()) / 2;
                                int y = (getHeight() - background.getHeight()) / 2;
                                graphics.drawImage(background, y, y, this);
                            }
    
                            // Render to graphics
                            // ...
                            // Dispose the graphics
                            graphics.dispose();
    
                            // Repeat the rendering if the drawing buffer contents
                            // were restored
                        } while (strategy.contentsRestored());
    
                        // Display the buffer
                        strategy.show();
    
                        // Repeat the rendering if the drawing buffer was lost
                    } while (strategy.contentsLost());
                }
            }
    
        }
    }