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);
	}
}


posted on 2012-07-21 02:32  java课程设计例子  阅读(288)  评论(0编辑  收藏  举报