Java Swing与线程的结合应用(一)

来源:互联网 发布:路由器mac地址怎么查 编辑:程序博客网 时间:2024/05/19 17:03

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(null)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;}@Overridepublic void run() {// TODO Auto-generated method stubint count=0;while(true){progressBar.setValue(++count);try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blockSystem.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);}}