您需要长时间运行并在之外的单独Thread中更新进度栏值
EDT。在大多数情况下,这
SwingWorker是一个很好的方法。因此,在
ActionListener该按钮中,应将长时间运行的线程与EDT分开。您可以赤手空拳来完成此任务,
Thread并且专门
SwingWorker针对此类情况设计:
package graphics;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.Jframe;import javax.swing.JOptionPane;import javax.swing.JProgressBar;import javax.swing.SwingUtilities;import javax.swing.SwingWorker;public class GraphicDev extends Jframe{ private static final long serialVersionUID = 679207429168581441L; // private static final int frame_WIDTH = 300; private static final int frame_HEIGHT = 100; private int percent; private JProgressBar progress; public GraphicDev() { Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); setBounds(dim.width/2-frame_WIDTH/2, dim.height/2-frame_HEIGHT/2, frame_WIDTH, frame_HEIGHT); setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); // setLayout(new FlowLayout()); // progress = new JProgressBar(0, 100); progress.setStringPainted(true); // JButton actButton = new JButton("Start!"); actButton.addActionListener(new ActionListener() {@Override public void actionPerformed(ActionEvent e) { new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { for (long i = 0; i < 10000000000000L; i++) { System.out.println(i); if(i%200000 == 0){ progress.setValue(percent++); } if(percent >= 100){ break; } } return null; } @Override protected void done() { JOptionPane.showMessageDialog(GraphicDev.this, "Done!"); } }.execute(); } }); // add(actButton); add(progress); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { GraphicDev g = new GraphicDev(); g.setVisible(true); } }); }}
希望这会有所帮助。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)