package itheima008; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class JProgressBarDemo2 { public static void main(String[] args) { new JProgressBarDemo2().init(); } JFrame jf = new JFrame("测试进度条"); JCheckBox selected = new JCheckBox("不确定进度条"); JCheckBox noBoder = new JCheckBox("没有边框"); JProgressBar bar = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100); private void init() { selected.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean se = selected.isSelected(); bar.setIndeterminate(se); bar.setStringPainted(!se); } }); noBoder.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean s = noBoder.isSelected(); bar.setBorderPainted(!s); } }); Box box = Box.createVerticalBox(); box.add(selected); box.add(noBoder); bar.setBorderPainted(true); bar.setStringPainted(true); jf.setLayout(new FlowLayout()); jf.add(box); jf.add(bar); // for (int x = 0; x <=100; x++) { // bar.setValue(x); // try { // Thread.sleep(10); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // } MyRunnable runnable = new MyRunnable(bar.getMaximum()); //启动线程 new Thread(runnable).start(); //设置定时器 Timer timer = new Timer(100, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int current = runnable.current; bar.setValue(current); } }); timer.start(); bar.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if(runnable.max ==bar.getValue()){ timer.stop(); } } }); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.pack(); jf.setVisible(true); } private class MyRunnable implements Runnable { private int current = 0; private int max; public MyRunnable(int max) { this.max = max; } public int getMax() { return max; } public void setMax(int max) { this.max = max; } @Override public void run() { while (current < max) { try { Thread.currentThread().sleep(50); current++; } catch (InterruptedException e) { e.printStackTrace(); } } } } }