Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8426911
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T04:39:26+00:00 2026-06-10T04:39:26+00:00

I have been following the Java Game Programming for Beginners tutorial series, and wished

  • 0

I have been following the Java Game Programming for Beginners tutorial series, and wished to experiment by applying a background image. Unfortunately, when I render it through the paintComponent method, it moves with my sprite (albeit at one unit continuously as opposed to five); and when I render it through the paint method, I get a strange, flickering box that matches the color designated in the setBackground (color) property of the JFrame and it moves with the sprite identically to that of the prior instance (within paintComponent).

How might I code the image so as to remain static, as a background should be?

Code:

public class JavaGame extends JFrame{

int x, y;
private Image dbImage;
private Graphics dbg;
Image ghost;
Image bg;


public class AL extends KeyAdapter{
    public void keyPressed(KeyEvent e){
        int keyCode = e.getKeyCode();

        if(keyCode == e.VK_LEFT){
            if(x <= 8)
                x = 8;
            else
                x += -5;
        }
        if(keyCode == e.VK_RIGHT){
            if(x >= 235)
                x = 235;
            else
                x += +5;
        }
        if(keyCode == e.VK_UP){
            if(y <= 18)
                y = 18;
            else
                y += -5;
        }
        if(keyCode == e.VK_DOWN){
            if(y >= 235)
                y = 235;
            else
                y += +5;
        }
    }
    public void keyReleased(KeyEvent e){

    }

}

public JavaGame(){
    //Load images
    ImageIcon i = new ImageIcon("C:/Users/Taylor/workspace/Java game/src/ghost.png");
    ghost = i.getImage();

    ImageIcon j = new ImageIcon("C:/Users/Taylor/workspace/Java game/src/bg.png");
    bg = j.getImage();

    //Game properties
    addKeyListener(new AL());
    setTitle("Java Game");
    setSize(500, 500);
    setResizable(false);
    setVisible(true);
    setBackground(Color.GRAY);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    x = 150;
    y = 150;
}

public void paint(Graphics g){
    g.drawImage(bg, 0, 0, null);

    dbImage = createImage(getWidth(), getHeight());
    dbg = dbImage.getGraphics();
    paintComponent(dbg);
    g.drawImage(dbImage, x, y, this);
}

public void paintComponent(Graphics g){
    g.setColor(Color.WHITE);
    g.drawImage(ghost, x, y, this);

    repaint();
}


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

}

Pictures:

rendered through 'paint'
rendered through 'paintComponent'

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T04:39:27+00:00Added an answer on June 10, 2026 at 4:39 am

    Were you copy/pasting code at random? That is what it looked like. There were so many odd aspects to that code that I did not document them all (a good one for code review, maybe). The example uses an asynchronous method to load the images (in order to get the animated image, animating). Use ImageIO.read(URL) for a synchronous way to load static images.

    Here are some brief tips:

    1. By the time this becomes deployed, the images will likely become an embedded resource and will not be accessible by File object. Add them to the run-time class-path and access them by URL.
    2. Swing GUIs should be started and altered on the EDT (see the change to the main()).
    3. Always call super.paint(g); (or paintComponent(g)) at the start of the method.
    4. Don’t extend frame, don’t paint to a top level component. Instead extend panel and override paintComponent(). Add the panel to the frame.

    Code

    import java.awt.*;
    import java.awt.event.*;
    import java.net.URL;
    import javax.swing.*;
    
    public class JavaGame extends JPanel {
    
        int x, y;
        private Image dbImage;
        private Graphics dbg;
        Image ghost;
        Image bg;
    
        public class AL extends KeyAdapter {
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
    
                if (keyCode == e.VK_LEFT) {
                    if (x <= 8)
                        x = 8;
                    else
                        x += -5;
                }
                if (keyCode == e.VK_RIGHT) {
                    if (x >= 235)
                        x = 235;
                    else
                        x += +5;
                }
                if (keyCode == e.VK_UP) {
                    if (y <= 18)
                        y = 18;
                    else
                        y += -5;
                }
                if (keyCode == e.VK_DOWN) {
                    if (y >= 235)
                        y = 235;
                    else
                        y += +5;
                }
            }
    
            public void keyReleased(KeyEvent e) {
            }
        }
    
        public JavaGame() throws Exception {
            // Load images
            //ImageIcon i = new ImageIcon(
                //  "C:/Users/Taylor/workspace/Java game/src/ghost.png");
            URL urlGhost = new URL("http://1point1c.org/gif/thum/plnttm.gif");
            ghost = Toolkit.getDefaultToolkit().createImage(urlGhost);
    
            //ImageIcon j = new ImageIcon(
                //  "C:/Users/Taylor/workspace/Java game/src/bg.png");
            URL urlBG = new URL("http://pscode.org/media/stromlo2.jpg");
            bg = Toolkit.getDefaultToolkit().createImage(urlBG);
            
            setFocusable(true);
    
            // Game properties
            addKeyListener(new AL());
            x = 150;
            y = 150;
            
            ActionListener al = new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    repaint();
                }
            };
            Timer timer = new Timer(50,al);
            timer.start();
        }
    
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(bg, 0, 0, null);
    
            //dbImage = createImage(getWidth(), getHeight());
            //dbg = dbImage.getGraphics();
            //paintComponent(dbg);
            g.drawImage(dbImage, x, y, this);
    
            g.setColor(Color.WHITE);
            g.drawImage(ghost, x, y, this);
    
            //repaint();
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    try {
                        JFrame f = new JFrame("Java Game");
                        f.setSize(500, 500);
                        f.setResizable(false);
                        f.setVisible(true);
                        f.setBackground(Color.GRAY);
                        f.setContentPane(new JavaGame());
                        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Have been following this fabulous tutorial . Being new to Javascript and functional programming,
I have been following the affableBean tutorial from the NetBeans site located here .
I have been following a tutorial on how to write a basic tile map
I have been following the tutorial on Microsofts website and they use GameTime to
I have been following a short tutorial to build a tab menu on my
I have been following this tutorial and everything was going nice and easy until
So I have been working on a 2 player Tic-Tac-Toe game in java that
i have been following this tutorial for the pagerAdapter. http://mobile.tutsplus.com/tutorials/android/android-user-interface-design-horizontal-view-paging/ My problem is that
Im very new to android/java and have been following a few youtube tutorials and
I've been following a tutorial here . So far i have a Gameview and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.