简体   繁体   中英

race condition when calling super.paint jframe

I'm trying to fill the entire canvas with fillRect . Whenever I include super.paint() in the beginning of the overridden paint method, super.paint() sometimes gets called after the fillRect , causing unpredictable behavior on whether super.paint() gets drawn first or drawRect .

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;

public class DebugJFrameRace extends JFrame {
    public DebugJFrameRace () {
        super("Debug race");
        this.setVisible(true);
        this.setSize(600, 600);
        this.repaint();
    }

    public void paint(Graphics g) {
        super.paint(g);
        
        // clear background
        g.setColor(Color.black);
        g.fillRect(0, 0, 600, 600);
        
        System.out.println("Finished");
    }

    public static void main(String[] args) {
        DebugJFrameRace app = new DebugJFrameRace ();
        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }


}

I don't have problems with the posted code.

I'm not really sure what it is designed to demonstrate. A black background is always painted.

However, the posted code does not follow Swing guidelines:

  1. All Swing components should be created and updated on the Event Dispach Thread (EDT) . This is done by using SwingUtilities.invokeLater(...) . Read the section from the Swing tutorial on Concurrency for more information and examples on how to better structure your code. Not executing the code on the EDT can cause random problems.

  2. You should not override paint() in a JFrame. Custom painting is done by overriding paintComponent(...) on a JPanel and then you add the panel to the frame. Read the section from the Swing tutorial on Custom Painting for more information and working examples.

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