How to Solve the window flicker problem caused by AWT components

I believe that many people will encounter the problem of window flicker when using AWT components, but this problem will not occur when using swing components. Well, I have also encountered such problems when using AWT components.

First of all, let’s talk about why window flicker occurs. AWT is the abbreviation of abstract window toolbox. It provides a user interface for writing graphical user interface. Through this interface, you can inherit many methods and save a lot of work. AWT also enables applications to better interact with users. The container in AWT is a special component. It can contain other components, that is, the component method can be stored in the container. The container class is a subclass of the component class used to store other components, and the frame class is a subclass of the component. The frame class is used to create a window with a title bar and a border. Here, you can create your own interface by inheriting the frame class.

In AWT, the order of redrawing the form canvas is repeat() – & gt; update()—> paint(); The default Upadate () has its own clearrect () method, that is, the screen clearing function. When the program runs, we call the repaint () method to refresh, which will cause the screen to just empty and continue to call the paint () method to draw on the form, which will cause the flicker problem!

Therefore, we only need to use our double buffer technology to add a picture to the original flickering place when the screen is clear, that is, to establish a buffer. When there is no picture loaded, the picture will be loaded from the buffer, which can solve the flickering problem.

When solving the problem, double buffering is directly performed in the paint () method. The code is as follows:

//Double buffering to solve the flickering problem
        // If it's swing it will avoid the window flicker problem.
            private Image offScreenImage = null;
              public void update(Graphics g) {
                if(offScreenImage == null) {
        //This is the width and height of the game window
                      offScreenImage = this.createImage(1067, 600);
                      
                }     
                Graphics gOff = offScreenImage.getGraphics();
                paint(gOff);
                g.drawImage(offScreenImage, 0, 0, null);
            }

Similar Posts: