繁体   English   中英

关闭程序时不回答

[英]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();
}
}

问题是,您在Eventdispatching线程中处于睡眠状态。

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

次要问题。 您应该从画图调用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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM