简体   繁体   中英

Drawn graphics flicker and then disappear when resizing window

The goal here is that I can click a color and shape, then two points on the figuresPanel. That colored shape is filled in on the figuresPanel, and I can add shapes on top of each other etc. I also need the current date to be displayed in the corner of the figuresPanel, on top of all the painted shapes. I am able to create shapes (though they always cover the date) no problem, but whenever I resize or minimize the window, all the painted shapes disappear. I've tried implementing quite a few different methods from Graphics (update, paint, redraw, etc.) and haven't found one that corrects this issue. I thought paintComponent() would take care of all that, but apparently not. Feel free to point out anything that could be implemented in a better way, always happy to learn something new.

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            drawFigures();
            figuresPanel.add(dateLabel, c);
        }

        @Override
        public Dimension getPreferredSize() {
            return (new Dimension(800, 600));
        }

        private void addFigure(Figure figure) {
            figureList.add(figure);
            listArea.append(figure.toString() + "\n");
            figure.fill(getGraphics());
        }

        private void drawFigures() {
            for (Figure f : figureList) {
                f.fill(getGraphics());
            }
        }

I would suggest a few things that might help you.

  1. In your method drawFigures() instead of using getGraphics() , why don't you pass the instance of Graphics in paintComponentMethod as a parameter to the method and use it to draw the object. This will make sure that you are drawing on the same instance of the Graphics that you are using to paint.

  2. In your method addFigure(Figure figure) I would suggest you remove the line figure.fill(getGraphics()); , to draw the object completely. Instead in your mouseClicked(MouseEvent event) method after your switch statement insert:

     revalidate(); repaint(); 

    This should actually take care of the drawing of the objects are done exactly on the same Graphics object that is being used to display the components.

I hope that this shall be helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM