Why does this while loop prevent paint method from working correctly?

大城市里の小女人 提交于 2021-02-17 03:39:10

问题


Here's my code:

package javaapplication2;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class JavaApplication2 extends JPanel {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Simple Sketching Program");
        frame.getContentPane().add(new JavaApplication2());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.setVisible(true);
    }

    @Override
    public void paint(Graphics g) {
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, getSize().width, getSize().height);

        while(true) {
            delay(1000);
        }
    }
}

I'm still trying to get the hang of things here. Now if the while(true) loop is commented out, it works fine, and the screen is covered in black. I've even put it in repaint() and called it from paint, and that does the same thing. I'm sure I'm miles from making this fine. If there's things I'm doing wrong, could you inform me? I've been looking everywhere to get this to work, and couldn't find anything that applied. Thank you.


回答1:


Because painting happens in the Event Dispatch Thread, and you're blocking it with your obvious infinite loop. This will prevent any further painting from happening, events from being processed, and anything else that happens inside the EDT.

That's why you never perform long running operations on EDT, but use a SwingWorker or other mechanism instead.



来源:https://stackoverflow.com/questions/33508805/why-does-this-while-loop-prevent-paint-method-from-working-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!