关闭程序时不接听

Not answering when you close the program

我有一个由 fillrect()、drawrect() 和 thread.sleep() 制作的进度条。问题是当我想关闭程序或调整框架大小时,进度条停止并且程序没有响应。我正在寻找一种不使用 JPregressBar() 来执行此进度条的替代方法,如果我按下关闭,框架将关闭。
这是代码:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;

import javax.swing.*;

public class Main extends JFrame{

private int num1, num2, width=0, g1;

public Main(){
    this.setTitle("Progressbar with rectangles");
    this.setSize(500, 500);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
    this.setResizable(true);
}
public void paint(Graphics g){
    g.setColor(Color.RED);
    g.drawRect(40, 40, 300, 20);

    g.setColor(Color.BLACK);

    for(width=0; width<300; width++){   
        g.fillRect(40,40,width,20);
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
}
}



public static void main(String[]args){
    Main m=new Main();
}
}

问题是,您在事件调度线程中休眠。

您必须在新线程中完成工作。

第二个问题。你应该从 paint 中调用 superMethod。

每次你想重画。调用 repaint() :)

private int num1, num2, width = 0, g1;

public Main() {
    this.setTitle("Progressbar with rectangles");
    this.setSize(500, 500);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
    this.setResizable(true);

    Main main  = this;

    Thread t = new Thread( new Runnable() {
        public void run() {

            for(width=0; width<300; width++) {

                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {

                        main.repaint();
                    }
                });


                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            }
        }
    });

    t.start();
}

@Override
public void paint(Graphics g) {

    super.paint(g);

    g.setColor(Color.RED);
    g.drawRect(40, 40, 300, 20);

    g.setColor(Color.BLACK);

    g.fillRect(40, 40, width, 20);

}

public static void main(String[] args) {
    Main m = new Main();
}