我有一个由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();
}
}
答案 0 :(得分:0)
问题是,你在Eventdispatching Thread中睡觉了。
你必须在一个新的线程中完成你的工作。
棘手的问题。你应该从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();
}