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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T04:07:57+00:00 2026-06-12T04:07:57+00:00

I trying to create a JPanel that draws rectangles. The Panel needs to draw

  • 0

I trying to create a JPanel that draws rectangles. The Panel needs to draw alot of rectangles, but they dont move.
One solution to my problem was to create an list with all the rectangles i already created and draw they all in every call of “Paint”. But there is a lot of rectangles and it slows the computer.
I also tried to use repaint(x, y, height, width) to rapaint just the space of the new rectangle but it did not work. (JPanel keeps erasing previous rectangles.)
In sort, i need to draw rectangles that wont disappear every paint. Or a paint method that wont erase previous draws, or wont paint the background.
That is part of my JPanel class:

class MyPanel extends JPanel{
  private int x, y, size;
  private Color c;
  public void DrawRect(int x, int y, int size, Color c){
      this.x = x;
      this.y = y;
      this.size = size;
      this.c = c;
      repaint();
  }
  @Override
    public void
    paint(Graphics g) {

        g.setColor(c);
      g.fillRect(x, y, size, size);
    }

}

  • 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-12T04:07:58+00:00Added an answer on June 12, 2026 at 4:07 am
    1. Don’t override paint WITHOUT VERY, VERY good reason…use paintComponent instead
    2. Always call super.paintXxx, these methods do a lot in the background, failing to call super is only going to come back and haunt you.
    3. If you’re using multiple panes as rectangles, make the MyPanel transparent.

    Paint’s are stateless. There is no connection between the last paint and the next. On each paint request you are expected to update the entire state.

    Andrew’s suggest of double buffering (or back buffering) is and excellent one, and I highly encourage you to have a look an implementing it.

    In the mean time, I put this little example together…

    enter image description here

    Basically, you press and hold the mouse button and it will randomly add another rectangle to the panel every 40 milli-seconds (roughly 25 frames a second).

    I got this up to a 1000 rects without any issue, was able to resize the window without and issue or obviously slow down…

    public class MyPanel extends JPanel {
    
        private List<MyRectangle> lstShapes;
        private Timer populate;
    
        public MyPanel() {
    
            lstShapes = new ArrayList<MyRectangle>(25);
    
            populate = new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
    
                    int x = (int) (Math.random() * getWidth());
                    int y = (int) (Math.random() * getHeight());
                    int width = (int) (Math.random() * (getWidth() / 4));
                    int height = (int) (Math.random() * (getHeight() / 4));
    
                    if (x + width > getWidth()) {
                        x = getWidth() - width;
                    }
                    if (y + height > getHeight()) {
                        y = getHeight() - height;
                    }
    
                    Color color = new Color(
                            (int) (Math.random() * 255),
                            (int) (Math.random() * 255),
                            (int) (Math.random() * 255));
    
                    lstShapes.add(new MyRectangle(x, y, width, height, color));
                    repaint();
                }
            });
            populate.setInitialDelay(0);
            populate.setRepeats(true);
            populate.setCoalesce(true);
    
            addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    populate.restart();
                }
    
                @Override
                public void mouseReleased(MouseEvent e) {
                    populate.stop();
                }
            });
    
        }
    
        @Override
        protected void paintComponent(Graphics g) {
    
            super.paintComponent(g);
    
            Graphics2D g2d = (Graphics2D) g;
            for (MyRectangle rect : lstShapes) {
                rect.paint(g2d);
            }
    
            FontMetrics fm = g2d.getFontMetrics();
            String text = Integer.toString(lstShapes.size());
    
            g2d.setColor(getForeground());
            g2d.drawString(text, getWidth() - fm.stringWidth(text), getHeight() - fm.getHeight() + fm.getAscent());
    
        }
    
        public class MyRectangle extends Rectangle {
    
            private Color color;
    
            public MyRectangle(int x, int y, int width, int height, Color color) {
                super(x, y, width, height);
                this.color = color;
            }
    
            public Color getColor() {
                return color;
            }
    
            public void paint(Graphics2D g2d) {
    
                g2d.setColor(getColor());
                g2d.fill(this);
    
            }
        }
    }
    

    have a go, it’s fun 😉

    ps- I got to up to over 5000 rectangles before I noticed a slow down (I modified the code down to a 10 milli second delay and was adding 10 new rectangles per tick)

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

Sidebar

Related Questions

I am trying to create a panel with pictures that are changed with the
I'm trying to create a JPanel that displays webpages. I've gotten to the stage
Trying to create a black line in my view to separate text blocks but
Trying to create a new Dedicated Cache Role in Windows Azure but get the
**Hello, I'm trying to create an archiver in java. This means that I am
I am trying to create a layout that will looking like: +---+--------+---+ | |
I'm trying to create a application where the taskbar and the JPanel(for example) has
I am trying to create a GUI that allows someone to set up an
I'm trying to create a custom timer that will record cumulative time passage separated
I am trying to create a jLabel that switches text messages via Timer. Currently,

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.