为什么这个while循环会阻止Paint方法正常工作

为什么这个while循环会阻止Paint方法正常工作

本文介绍了为什么这个while循环会阻止Paint方法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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);
        }
    }
}

我仍在设法解决问题.现在,如果注释了while(true)循环,则它可以正常工作,并且屏幕被黑色覆盖.我什至将它放在repaint()中,并从paint中调用它,并且做同样的事情.我敢肯定,要做到这一点还很遥远.如果我做错了什么,您能告诉我吗?我一直在到处寻找使它起作用的方法,但是找不到任何适用的方法.谢谢.

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.

推荐答案

由于绘画发生在Event Dispatch Thread中,因此您用明显的无限循环来阻止它.这样可以防止发生进一步的绘画,处理事件以及EDT内部发生的任何其他事情.

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.

这就是为什么您永远不会在EDT上执行长时间运行的操作,而是使用SwingWorker或其他机制的原因.

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

这篇关于为什么这个while循环会阻止Paint方法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:41