Java Swing与线程的结合应用


Java Swing与线程的结合应用:

  1. package com.han;  
  2.   
  3. import java.awt.*;  
  4. import javax.swing.*;  
  5. /** 
  6.  * 使用了线程中断在swing进度条中的应用,在run()中调用JProgressBar的setValue()方法。 
  7.  * <p> 
  8.  * 本例应用了线程的中断,2种中断方法: 
  9.  * <ul> 
  10.  * <li>运用interrupt()方法</li> 
  11.  * <li>在run()中使用无限循环,然后用一个布尔什标记去控制循环的停止</li> 
  12.  * </ul> 
  13.  * 另外,还有内部类与匿名内部类的分别使用。 
  14.  * 
  15.  * @author HAN 
  16.  * 
  17.  */  
  18.   
  19. @SuppressWarnings("serial")  
  20. public class ThreadAndSwing extends JFrame{  
  21.     static Thread thread;  
  22.     JProgressBar progressBar;  
  23.     public ThreadAndSwing(){  
  24.         progressBar=new JProgressBar();  
  25.         progressBar.setStringPainted(true);  
  26.         Container container=getContentPane();  
  27.         container.add(progressBar, BorderLayout.NORTH);//在不指定布局管理器的情况下,默认使用BorderLayout。 若不使用布局管理器,需明确说明setLayout(new BorderLayout())   
  28.           
  29.         this.setTitle("线程中断在Swing进度条的使用");  
  30.         this.pack();  
  31.         this.setVisible(true);  
  32.         this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);  
  33.           
  34.         this.creatThread();  
  35.         thread.start();  
  36. //       thread_instance.setContinue(false); //另一种中断线程方式   
  37.         thread.interrupt();  
  38.     }  
  39.       
  40.     class Thread_instance implements Runnable{  
  41.         boolean isContinue=true;  
  42.         public void setContinue(boolean b){  
  43.             this.isContinue=b;  
  44.         }  
  45.         @Override  
  46.         public void run() {  
  47.             // TODO Auto-generated method stub   
  48.             int count=0;  
  49.               
  50.             while(true){  
  51.                 progressBar.setValue(++count);  
  52.                 try {  
  53.                     Thread.sleep(1000);  
  54.                 } catch (InterruptedException e) {  
  55.                     // TODO Auto-generated catch block   
  56.                     System.out.println("当前程序被中断");  
  57.                     break;  
  58.                 }  
  59.                 if(!isContinue){  
  60.                     break;  
  61.                 }  
  62.             }  
  63.             System.out.println("here");  
  64.         }  
  65.     }  
  66.     void creatThread(){  
  67.         thread=new Thread(new Thread_instance());  
  68.     }  
  69.     static void init(JFrame frame,int width,int height){  
  70.         frame.setSize(width,height);  
  71.     }  
  72.     public static void main (String[] args){  
  73.         init(new ThreadAndSwing(),300,100);  
  74.     }  
  75. }  
  • 1
  • 2
  • 3
  • 下一页
【内容导航】
第1页:(一) 第2页:(二)
第3页:(三)

相关内容