java 进度条 中止_取消进度条的一个示例

执行下看看结果

成功了

第二次点击“Start ProgressBar”按钮,进度条又可以正常工作了

O了

把最后的代码粘一份:

package chapter4;

import org.jvnet.substance.skin.CremeCoffeeSkin;

import org.jvnet.substance.skin.SubstanceAutumnLookAndFeel;

import org.jvnet.substance.skin.SubstanceSaharaLookAndFeel;

import javax.swing.*;

import javax.swing.plaf.metal.MetalProgressBarUI;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.concurrent.TimeUnit;

/**

* Created by MyWorld on 2016/3/24.

*/

public class SwingJProgressBarDemo {

private static Thread thread = null;

public static void main(String[] args) throws UnsupportedLookAndFeelException {

UIManager.setLookAndFeel(new SubstanceAutumnLookAndFeel());

SubstanceSaharaLookAndFeel.setSkin(new CremeCoffeeSkin());

SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

new SwingJProgressBarDemo().initGUI();

}

});

}    private void initGUI() {

final JFrame frame = new JFrame("JProgressBarDemo");

frame.setSize(400, 200);

frame.setLocationRelativeTo(null);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(new FlowLayout());

final JProgressBar progressBar = new JProgressBar();

progressBar.setOrientation(JProgressBar.HORIZONTAL);

progressBar.setSize(200, 100);

progressBar.setMinimum(0);

progressBar.setMaximum(100);

progressBar.setBorderPainted(true);

progressBar.setUI(new MetalProgressBarUI());

progressBar.setBackground(Color.BLUE);

progressBar.setForeground(Color.GREEN);

progressBar.setStringPainted(true);

frame.add(progressBar);

JButton btnStart = new JButton("Start ProgressBar");

final Runnable runnable = new Runnable() {

@Override

public void run() {

try {

for (int i = 0; i <= 10; i++) {

final int finalI = i;

SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

progressBar.setValue(finalI * 10);

}

});

TimeUnit.SECONDS.sleep(1);

}

} catch (InterruptedException e1) {

e1.printStackTrace();

}

}

};

ActionListener listener = new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

thread = new Thread(runnable);

thread.start();

}

};        btnStart.addActionListener(listener);

frame.add(btnStart);        JButton btnCancel = new JButton("Cancel the task");

btnCancel.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

if (thread == null || !thread.isAlive()) {

return;

}

thread.interrupt();

SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

progressBar.setValue(0);

}

});

}

});

frame.add(btnCancel);

frame.setVisible(true);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值