在用Java绘制面板之前暂停

在用Java绘制面板之前暂停,java,swing,jpanel,paintcomponent,thread-sleep,Java,Swing,Jpanel,Paintcomponent,Thread Sleep,我试图通过在两幅连续的画作之间加上一个停顿来减缓这幅画的速度Thread.sleep()显然不起作用。代码如下: import javax.swing.*; import java.awt.*; public class Sa { int x = 70; int y = 70; public static void main(String[] args) { Sa gui = new Sa(); gui.go(); }

我试图通过在两幅连续的画作之间加上一个停顿来减缓这幅画的速度
Thread.sleep()
显然不起作用。代码如下:

import javax.swing.*;
import java.awt.*;

public class Sa {
    int x = 70;
    int y = 70;

    public static void main(String[] args) {
        Sa gui = new Sa();
        gui.go();
    }

    public void go() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        MyDrawPanel drawPanel = new MyDrawPanel();
        frame.getContentPane().add(drawPanel);

        frame.setSize(300, 300);
        frame.setVisible(true);

        for(int i=0; i<130; i++) {
            x++;
            y++;
            drawPanel.repaint();
            try {
                Thread.sleep(1500);
            } catch(Exception ex) {}
        }

    }

    class MyDrawPanel extends JPanel {
        public void paintComponent(Graphics g) {
            g.setColor(Color.white);
            g.fillRect(0, 0, this.getWidth(), this.getHeight());
            Thread.sleep(1500); // will not work!!
            g.setColor(Color.green);
            g.fillOval(x, y, 80, 40);
        }
    }
}
import javax.swing.*;
导入java.awt.*;
公共类Sa{
int x=70;
int y=70;
公共静态void main(字符串[]args){
Sa gui=新Sa();
gui.go();
}
公开作废go(){
JFrame=新JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel drawPanel=新建MyDrawPanel();
frame.getContentPane().add(drawPanel);
框架。设置尺寸(300300);
frame.setVisible(true);
对于(int i=0;iRemove
Thread.sleep()
inside
paint()
方法,不需要它,其次,需要捕获
Thread.sleep()
中断异常,它可能在编译时出错:

  g.setColor(Color.white);
    g.fillRect(0, 0, this.getWidth(), this.getHeight());
    //Thread.sleep(1500); // will not work!! (DONT NEED this
    g.setColor(Color.green);
    g.fillOval(x, y, 80, 40);
你看了吗?

删除
Thread.sleep()
内部
paint()
方法,不需要它,第二,你
Thread.sleep()
需要捕获
interruptedeexception
,它可能在编译时出错:

  g.setColor(Color.white);
    g.fillRect(0, 0, this.getWidth(), this.getHeight());
    //Thread.sleep(1500); // will not work!! (DONT NEED this
    g.setColor(Color.green);
    g.fillOval(x, y, 80, 40);

你看过了吗?

你看过了吗?我不是这方面的专家,但我不认为你可以直接从运行主程序的线程中完成所有Swing任务,看起来你就是这么做的。你不能这样做。睡眠当前线程将阻止事件调度线程处理当前问题所以在
paintComponent
方法返回之前,不会绘制任何内容。问题是,为什么?你想实现什么…?你看过了吗?我不是这方面的专家,但我不认为你可以直接从运行主程序的线程中执行所有Swing操作,而且看起来像这样这是您正在做的。您不能这样做。睡眠当前线程将停止事件调度线程处理当前绘制进程。因此,在
paintComponent
方法返回之前,不会绘制任何内容。问题是,为什么?您试图实现的是什么。。。??