Results 1 to 2 of 2
  1. #1
    jwl
    jwl is offline Member
    Join Date
    Jul 2012
    Posts
    93
    Rep Power
    0

    Default Draw background image

    Hi,

    I am using a sample jpg picture from my computer stored in the src of the program.
    Java Code:
    package game1;
    
    import java.awt.*;
    import javax.swing.*;
    
    public class Game1 extends JFrame {
        private Insets insets;
        private final int WIDTH = 800, HEIGHT = 600;
        private Graphics g;
        private Image imageBuffer;
    
        public Game1() {
            setVisible(true);
            insets = getInsets();
            setSize(WIDTH + insets.left + insets.right, HEIGHT + insets.top + 
                    insets.bottom);
            setTitle("Game1");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setLocationRelativeTo(null);
            setResizable(false);
            if (((imageBuffer = createImage(WIDTH, HEIGHT)) != null) && 
                    ((g = imageBuffer.getGraphics()) != null))
                drawGame();
            else
                System.exit(1);
    }
    
        public void paint(Graphics g) {
            if (imageBuffer != null)
                g.drawImage(imageBuffer, insets.left, insets.top, null);
    }
        
        
        private void drawGame() {
            Image img;
            img = Toolkit.getDefaultToolkit().createImage("Lighthouse.jpg");
            g.drawImage(img, insets.left, insets.top, null);
            repaint();
        }
        
        public static void main(String[] args) {
            Game1 game = new Game1();
        }
    }
    It is not displaying the picture on the window.
    Any help?

  2. #2
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default Re: Draw background image

    Don't paint directly on a JFrame, instead subclass JPanel and do your drawing in the paintComponent() method. Then simply add the panel to your jframe!

Similar Threads

  1. How to draw over a jpg image
    By vagras in forum New To Java
    Replies: 2
    Last Post: 12-28-2011, 04:27 AM
  2. Replies: 1
    Last Post: 07-28-2011, 08:48 AM
  3. Replies: 4
    Last Post: 11-25-2010, 02:22 AM
  4. Replies: 13
    Last Post: 09-29-2010, 10:55 PM
  5. Background image
    By leiferouis in forum New To Java
    Replies: 9
    Last Post: 03-08-2009, 05:49 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •