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 8758195
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T14:29:00+00:00 2026-06-13T14:29:00+00:00

I’m completely stuck on a problem i’m having with this program where I have

  • 0

I’m completely stuck on a problem i’m having with this program where I have to draw a city with swing. Basically what i’m trying to do is make it so that the windows don’t change every frame. I’ve tried just about everything I can think of and nothing has worked yet.

Here is the main class that draws everything

import java.applet.Applet;
import java.awt.*;
import java.util.*;
import javax.swing.JFrame;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

public class Skyline extends JFrame implements MouseMotionListener
{
    private int mX, mY; //Mouse cooddinates
    private Image mImage; //Image buffer
    //private Image mImage2; //Image buffer

    private int num = 0;

    private Building bldg1 = new Building(305, 110, 30);
    private Building bldg2 = new Building(380, 125, 170);
    private Building bldg3 = new Building(245, 200, 325);
    private Building bldg4 = new Building(470, 170, 555);
    private Building bldg5 = new Building(395, 200, 755);
    private Background bg = new Background();

    public void init ()
    {
    }

    public static void main(String []args)
    {
        Skyline f = new Skyline();

        f.setSize(1017, 661); //Sets size of window
        f.setTitle("Skyline"); //Sets title of window
        f.show();
    }

    public void paintOffscreen(Graphics page)
    {
        //Draws the background
        bg.draw(page);

        //Moving square
        num++;
        if (num > 1200)
            num = 0;
        page.setColor(Color.yellow);
        page.fillRect(num,100,100,100);

        //Draws the buildings
        bldg1.draw(page);
        bldg2.draw(page);
        bldg3.draw(page);
        bldg4.draw(page);
        bldg5.draw(page);

        //Mouse move square
        int s = 100;

        page.setColor(Color.yellow);
        page.fillRect(mX - s / 2, mY - s / 2, s, s);

        repaint();
    }

    //====================================BUFFER CODE========================================
    public void paint(Graphics g)
    {
        //Clear the buffer
        Dimension d = getSize();
        checkOffscreenImage();
        Graphics offG = mImage.getGraphics();
        offG.setColor(getBackground());
        offG.fillRect(0, 0, d.width, d.height);

        //Save frame to buffer
        paintOffscreen(mImage.getGraphics());

        //Draw the buffer
        g.drawImage(mImage, 0, 0, null);

    }

    private void checkOffscreenImage()
    {
        Dimension d = getSize();

        if (mImage == null || mImage.getWidth(null) != d.width || mImage.getHeight(null) != d.height)
            mImage = createImage(d.width, d.height);
    }
    //=======================================================================================


    //==================================MOUSE MOVE         CODE======================================
    public Skyline()
    {
        addMouseMotionListener(this);
        setVisible(true);
    }

    public void mouseMoved(MouseEvent me)
    {
        Graphics g = getGraphics();
        mX = (int) me.getPoint().getX();
        mY = (int) me.getPoint().getY();
        update(g);
        //repaint();
    }

    public void mouseDragged(MouseEvent me)
    {
        mouseMoved(me);
    }
    //=======================================================================================

}

And here is the window class that might be able to be fixed somehow.

import java.applet.Applet;
import java.awt.*;
import java.util.Random;
import javax.swing.JFrame;

public class Windows extends JFrame
{
    private Random gen = new Random();
    private int height, width, locX;
    private int onOff = 0;

    public Windows()
    {
        height = 305;
        width = 110;
        locX = 30;
    }

    public Windows(int height, int width, int locX)
    {
        this.height = height;
        this.width= width;
        this.locX = locX;
    }

    public void draw(Graphics page)
    {
    page.setColor (Color.darkGray);

    page.fillRect (locX, 550 - height, width, height);

        for (int i = 550 - height + 5; i < 550; i += 15)
        {
            for (int x = locX + 5; x < locX + width; x += 15)
            {
                onOff = gen.nextInt(2);

                if(onOff == 0)
                    page.setColor(Color.black);
                else
                    page.setColor(Color.yellow);

                page.fillRect (x,i,10,10);
            }
        }
    }
}

Heres the building class just in case.

import java.applet.Applet;
import java.awt.*;
import javax.swing.JFrame;

public class Building extends JFrame
{
    private int height, width, locX;
    private int onOff;
    private Windows windows1;// = new Windows(height, width, locX);

    public Building()
    {
        height = 305;
        width = 110;
        locX = 30;

        windows1 = new Windows(height, width, locX);
    }

    public Building(int height, int width, int locX)
    {
        this.width = width;
        this.height = height;
        this.locX = locX;

        windows1 = new Windows(height, width, locX);
    }

    public void draw(Graphics page)
    {
    page.setColor (Color.darkGray);

    page.fillRect (locX, 550 - height, width, height);

    windows1.draw(page);
    }
}

And the bg class just to be safe

import java.applet.Applet;
import java.awt.*;

public class Background extends Applet
{
    private int height, width;

    public Background()
    {
        height = 400;
        width = 2000;
    }

    public Background(int height, int width)
    {
        this.height = height;
        this.width = width;
    }

    public void draw(Graphics page)
    {
        //Draws the sky
        page.setColor(Color.cyan);
        page.fillRect(0,0,2000,2000);
        //Draws the grass
        page.setColor (Color.green);
        page.fillRect (0,500,width,height);
    }
}
  • 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-13T14:29:01+00:00Added an answer on June 13, 2026 at 2:29 pm

    A number of things jump out at me immediately…

    You’re trying to use a off screen buffer, but you’re recreating it each time you paint to the screen…

    public void paintOffscreen(Graphics page)
    {
        //Draws the background
        bg.draw(page);
    
        //Moving square
        num++;
        if (num > 1200)
            num = 0;
        page.setColor(Color.yellow);
        page.fillRect(num,100,100,100);
    
        //Draws the buildings
        bldg1.draw(page);
        bldg2.draw(page);
        bldg3.draw(page);
        bldg4.draw(page);
        bldg5.draw(page);
    
        //Mouse move square
        int s = 100;
    
        page.setColor(Color.yellow);
        page.fillRect(mX - s / 2, mY - s / 2, s, s);
    
        repaint();
    }
    

    Additionally, the last call in the method is to repaint. This is a bad idea. This could cause you paint method to be recalled, again and again and again…

    You would be better of rendering the backing buffer only when it needs to change…

    public void paint(Graphics g)
    {
        super.paint(g); // YOU MUST CALL super.paint!!!!  
    
        //Clear the buffer
        Dimension d = getSize();
        checkOffscreenImage();
    
        //Draw the buffer
        g.drawImage(mImage, 0, 0, null);
    
    }
    
    private void checkOffscreenImage()
    {
        Dimension d = getSize();
    
        if (mImage == null || mImage.getWidth(null) != d.width || mImage.getHeight(null) != d.height) {
            mImage = createImage(d.width, d.height);
            Graphics offG = mImage.getGraphics();
            offG.setColor(getBackground());
            offG.fillRect(0, 0, d.width, d.height);
    
            //Save frame to buffer
            paintOffscreen(offG);
            offG.dispose(); // If you create it, you must dispose of it...
        }
    }
    

    Now, this is going to raise some issues with invalidating the buffer. This can be achieved by overriding invalidate and setting the mImage to null

    public void invalidate() {  
        mImage = null;
        super.invalidate();
    }
    

    You’re extending most of your components from JFrame???

    Building, Window and Background do no painting of there own (from the content of Swing), you are simply calling the draw method. There is no need to extend from JFrame or JApplet, they’re adding no benefit to your program and are simply confusing the issues.

    You should, only very rarely, need to override paint on a top level container like JFrame. You are better off using something like JPanel and override the paintComponent method, if for no other reason, they (top level containers) aren’t double buffered.

    I would move the logic for Skyline into a JPanel and then add it to a JFrame for displaying – IMHO

    UPDATED

    I’ve gone through the code and updated it to work the (basic) way I think it should and found a couple of other things along the way…

    This this is a bad idea…

        public void mouseMoved(MouseEvent me) {
            Graphics g = getGraphics();
            mX = (int) me.getPoint().getX();
            mY = (int) me.getPoint().getY();
            update(g);
            //repaint();
        }
    

    There should never be any need for you to call update(Graphics), besides, the Graphics context you got is simply a snap shot of the last repaint. This will drastically slow you painting process any way, as it is repeatedly calling paint.

    So, this is my take…

    public class Skyline extends JFrame {
    
        private int num = 0;
        private Building bldg1 = new Building(305, 110, 30);
        private Building bldg2 = new Building(380, 125, 170);
        private Building bldg3 = new Building(245, 200, 325);
        private Building bldg4 = new Building(470, 170, 555);
        private Building bldg5 = new Building(395, 200, 755);
        private Background bg = new Background();
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException ex) {
                    } catch (InstantiationException ex) {
                    } catch (IllegalAccessException ex) {
                    } catch (UnsupportedLookAndFeelException ex) {
                    }
    
                    Skyline f = new Skyline();
    
                    f.setSize(1017, 661); //Sets size of window
                    f.setTitle("Skyline"); //Sets title of window
                    f.setVisible(true);
                }
            });
        }
    
        public Skyline() {
            setLayout(new BorderLayout());
            add(new SkyLinePane());
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        }
    
        public class SkyLinePane extends JPanel {
    
            private Image mImage; //Image buffer
            private boolean painting = false;
    
            private int mX, mY; //Mouse cooddinates
    
            public SkyLinePane() {
                addMouseMotionListener(new MouseAdapter() {
                    @Override
                    public void mouseMoved(MouseEvent me) {
                        mX = (int) me.getPoint().getX();
                        mY = (int) me.getPoint().getY();
                        repaint();
                    }
                });
    
            }
    
            protected void updateBuffer() {
                if (!painting && mImage == null) {
                    painting = true;
                    new BackgroundPainter(this).execute();
                }
            }
    
            //====================================BUFFER CODE========================================
            @Override
            public void paintComponent(Graphics g) {
                Dimension d = getSize();
                if (mImage != null) {
                    g.drawImage(mImage, 0, 0, null);
                } else {
                    updateBuffer();
                }
                g.setColor(Color.RED);
                g.drawOval(mX - 5, mY - 5, 10, 10);
            }
            //=======================================================================================
    
            protected void setBackground(Image image) {
                mImage = image;
                painting = false;
                repaint();
            }
        }
    
        public class BackgroundPainter extends SwingWorker<Image, Image> {
    
            private SkyLinePane skyLinePane;
    
            public BackgroundPainter(SkyLinePane skyLinePane) {
                this.skyLinePane = skyLinePane;
            }
    
            @Override
            protected Image doInBackground() throws Exception {
                Dimension d = skyLinePane.getSize();
    
                Image backgroundBuffer = null;
                if (d.width > 0 && d.height > 0) {
    
                    System.out.println("Paint offscreen...");
                    backgroundBuffer = createImage(d.width, d.height);
                    Graphics offG = backgroundBuffer.getGraphics();
                    offG.setColor(getBackground());
                    offG.fillRect(0, 0, d.width, d.height);
    
                    //Save frame to buffer
                    paintOffscreen(offG);
    
                    offG.dispose();
                    System.out.println("Done Paint offscreen...");
    
                }
    
                return backgroundBuffer;
            }
    
            @Override
            protected void done() {
                try {
                    skyLinePane.setBackground(get());
                } catch (ExecutionException exp) {
                    exp.printStackTrace();
                } catch (InterruptedException exp) {
                    exp.printStackTrace();
                }
            }
    
            public void paintOffscreen(Graphics page) {
                //Draws the background
                bg.draw(page);
    
                //Moving square
                num++;
                if (num > 1200) {
                    num = 0;
                }
                page.setColor(Color.yellow);
                page.fillRect(num, 100, 100, 100);
    
                //Draws the buildings
                bldg1.draw(page);
                bldg2.draw(page);
                bldg3.draw(page);
                bldg4.draw(page);
                bldg5.draw(page);
            }
        }
    
        //=======================================================================================
        public class Windows {
    
            private Random gen = new Random();
            private int height, width, locX;
            private int onOff = 0;
    
            public Windows() {
                height = 305;
                width = 110;
                locX = 30;
            }
    
            public Windows(int height, int width, int locX) {
                this.height = height;
                this.width = width;
                this.locX = locX;
            }
    
            public void draw(Graphics page) {
                page.setColor(Color.darkGray);
    
                page.fillRect(locX, 550 - height, width, height);
    
                for (int i = 550 - height + 5; i < 550; i += 15) {
                    for (int x = locX + 5; x < locX + width; x += 15) {
                        onOff = gen.nextInt(2);
    
                        if (onOff == 0) {
                            page.setColor(Color.black);
                        } else {
                            page.setColor(Color.yellow);
                        }
    
                        page.fillRect(x, i, 10, 10);
                    }
                }
            }
        }
    
        public class Building {
    
            private int height, width, locX;
            private int onOff;
            private Windows windows1;// = new Windows(height, width, locX);
    
            public Building() {
                height = 305;
                width = 110;
                locX = 30;
    
                windows1 = new Windows(height, width, locX);
            }
    
            public Building(int height, int width, int locX) {
                this.width = width;
                this.height = height;
                this.locX = locX;
    
                windows1 = new Windows(height, width, locX);
            }
    
            public void draw(Graphics page) {
                page.setColor(Color.darkGray);
    
                page.fillRect(locX, 550 - height, width, height);
    
                windows1.draw(page);
            }
        }
    
        public class Background {
    
            private int height, width;
    
            public Background() {
                height = 400;
                width = 2000;
            }
    
            public Background(int height, int width) {
                this.height = height;
                this.width = width;
            }
    
            public void draw(Graphics page) {
                //Draws the sky
                page.setColor(Color.cyan);
                page.fillRect(0, 0, 2000, 2000);
                //Draws the grass
                page.setColor(Color.green);
                page.fillRect(0, 500, width, height);
            }
        }
    }
    

    Basically, I moved the core rendering of the skyling to it’s own panel and used JComponent#paintComponent to render the skyline.

    I employed a SwingWorker to off load the rendering of the backing buffer to another thread, allowing the UI to remain responsive while the backing buffer was rendered.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
this is what i have right now Drawing an RSS feed into the php,
I have a small JavaScript validation script that validates inputs based on Regex. I
I have a French site that I want to parse, but am running into
I have this code to decode numeric html entities to the UTF8 equivalent character.
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
This could be a duplicate question, but I have no idea what search terms
I know there's a lot of other questions out there that deal with this

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.