易网时代-编程资源站
Welcome
微信登录
编程资源
图片资源库
蚂蚁家优选
PDF转换器
软件资源
软件开发
、
小程序制作
、
系统集成与运维
、
空间租用
、
硬件开发
、
视频监控
、
技术咨询与支持
——联系电话:0311-88999002/88999003
首页
/
操作系统
/
Linux
/
Java Swing与线程的结合应用
Java Swing与线程的结合应用:
package
com.han;
import
java.awt.*;
import
javax.swing.*;
/**
* 使用了线程中断在swing进度条中的应用,在run()中调用JProgressBar的setValue()方法。
* <p>
* 本例应用了线程的中断,2种中断方法:
* <ul>
* <li>运用interrupt()方法</li>
* <li>在run()中使用无限循环,然后用一个布尔什标记去控制循环的停止</li>
* </ul>
* 另外,还有内部类与匿名内部类的分别使用。
*
* @author HAN
*
*/
@SuppressWarnings
(
"serial"
)
public
class
ThreadAndSwing
extends
JFrame{
static
Thread thread;
JProgressBar progressBar;
public
ThreadAndSwing(){
progressBar=
new
JProgressBar();
progressBar.setStringPainted(
true
);
Container container=getContentPane();
container.add(progressBar, BorderLayout.NORTH);
//在不指定布局管理器的情况下,默认使用BorderLayout。 若不使用布局管理器,需明确说明setLayout(new BorderLayout())
this
.setTitle(
"线程中断在Swing进度条的使用"
);
this
.pack();
this
.setVisible(
true
);
this
.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this
.creatThread();
thread.start();
// thread_instance.setContinue(false); //另一种中断线程方式
thread.interrupt();
}
class
Thread_instance
implements
Runnable{
boolean
isContinue=
true
;
public
void
setContinue(
boolean
b){
this
.isContinue=b;
}
@Override
public
void
run() {
// TODO Auto-generated method stub
int
count=
0
;
while
(
true
){
progressBar.setValue(++count);
try
{
Thread.sleep(
1000
);
}
catch
(InterruptedException e) {
// TODO Auto-generated catch block
System.out.println(
"当前程序被中断"
);
break
;
}
if
(!isContinue){
break
;
}
}
System.out.println(
"here"
);
}
}
void
creatThread(){
thread=
new
Thread(
new
Thread_instance());
}
static
void
init(JFrame frame,
int
width,
int
height){
frame.setSize(width,height);
}
public
static
void
main (String[] args){
init(
new
ThreadAndSwing(),
300
,
100
);
}
}
收藏该网址
版权所有©石家庄振强科技有限公司2024
冀ICP备08103738号-5
网站地图