问题
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