swing 按钮不释放 (线程问题)

代码一:

package org.jivesoftware.pmsaas.business.domain;

import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import chrriis.dj.nativeswing.swtimpl.NativeInterface;
/**
 * 该类是包含着浏览器的外框,即启动时候首先出现的是一个swing的框
 * */
public class InternetBrowser{

 /**
  *
  */
 private static final long serialVersionUID = -3160632621097858320L;

 public InternetBrowser(final String url)
 {
  SwingUtilities.invokeLater(new Runnable() {
         public void run() {
             final JFrame frame = new JFrame();
//             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.getContentPane().add(new NetBrowser(url),
               BorderLayout.CENTER);

             frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
             frame.setLocationByPlatform(true);
             frame.setAlwaysOnTop(true);
//             frame.setUndecorated(true);
             frame.setSize(675,507);
//             frame.setUndecorated(true);
             frame.setResizable(false);

             frame.addWindowListener(new WindowAdapter(){
             public void windowIconified(WindowEvent e)
                {
             frame.setExtendedState(JFrame.ICONIFIED);
                }
             });
             frame.setVisible(true);

         }
         });
       
         NativeInterface.open();
         NativeInterface.runEventPump();
        
 }
}

 

package org.jivesoftware.pmsaas.business.domain;

import java.awt.BorderLayout;

import javax.swing.JPanel;

import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;
/**
 * 该类是一个浏览器lei
 * */
public class NetBrowser extends JPanel{

 /**
  *
  */
 private static final long serialVersionUID = -679703553152283868L;

  private JPanel webBrowserPanel;
     private JWebBrowser webBrowser;
     private String url;

     public NetBrowser(String url)
     {
          super(new BorderLayout());
          this.url = url;
          webBrowserPanel = new JPanel(new BorderLayout());
          webBrowser = new JWebBrowser();
          /**
             * native swing 官方API解释
             * navigate
  
  public boolean navigate(String resourceLocation)
  Navigate to a resource, with its location specified as a URL or path.
  Parameters:
  resourceLocation - the URL or path.
  Returns:
  true if the navigation was successful.
           * */
          webBrowser.navigate(url);
          webBrowser.setButtonBarVisible(false);
          webBrowser.setMenuBarVisible(true);
          webBrowser.setBarsVisible(false);
          webBrowser.setStatusBarVisible(false);
          //webBrowserPanel与webBrowser互相包含
          webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
          add(webBrowserPanel, BorderLayout.CENTER);
     }
}

 

出现问题代码:

private JPanel getJPanel(){
        // Get Workspace UI from SparkManager
      
       // Add own Tab.
       JPanel imgPanel=new JPanel();
       imgPanel.setLayout(new GridLayout(3,3,20,20));
      
        ib1=new RolloverButton(BusinessPluginRes.getString(BusinessPluginRes.ESTATERES_STR),BusinessPluginRes.getImageIcon(BusinessPluginRes.ESTATERES));
        ib2=new RolloverButton(BusinessPluginRes.getString(BusinessPluginRes.FEEMG_STR),BusinessPluginRes.getImageIcon(BusinessPluginRes.FEEMG));
        ib3=new RolloverButton(BusinessPluginRes.getString(BusinessPluginRes.FEEPJ_STR),BusinessPluginRes.getImageIcon(BusinessPluginRes.FEEPJ));
        ib4=new RolloverButton(BusinessPluginRes.getString(BusinessPluginRes.FEEST_STR),BusinessPluginRes.getImageIcon(BusinessPluginRes.FEEST));
        ib5=new RolloverButton(BusinessPluginRes.getString(BusinessPluginRes.FEETB_STR),BusinessPluginRes.getImageIcon(BusinessPluginRes.FEETB));
        ib6=new RolloverButton(BusinessPluginRes.getString(BusinessPluginRes.NOTE_STR),BusinessPluginRes.getImageIcon(BusinessPluginRes.NOTE));
        ib7=new RolloverButton(BusinessPluginRes.getString(BusinessPluginRes.RATECH_STR),BusinessPluginRes.getImageIcon(BusinessPluginRes.RATECH));
        ib8=new RolloverButton(BusinessPluginRes.getString(BusinessPluginRes.TABLEMG_STR),BusinessPluginRes.getImageIcon(BusinessPluginRes.TABLEMG));
        ib9=new RolloverButton(BusinessPluginRes.getString(BusinessPluginRes.TABLEST_STR),BusinessPluginRes.getImageIcon(BusinessPluginRes.TABLEST));
       /**
        * 
        * */
       ib1.addActionListener(new ActionListener() {
  
  @Override
  public void actionPerformed(ActionEvent e) {
        
          // TODO Auto-generated method stub
      new InternetBrowser("http://www.baidu.com");
        
  }
 });

 

出现的问题是: 按钮ib1 按下去之后无法释放 之后就无法产生浏览器窗口new InternetBrowser("http://www.baidu.com");

 

出现问题原因: 主线程上无法执行新的一个线程new InternetBrowser("http://www.baidu.com"); 线程里不会再产生线程。

因此解决办法:

参照 http://blog.csdn.net/bzwm/article/details/3895381#comments 

摘抄如下

---------------------------------------------------------------------------------------------------------------

现在我们要做一个简单的界面。

包括一个进度条、一个输入框、开始和停止按钮。

需要实现的功能是:

当点击开始按钮,则更新进度条,并且在输入框内把完成的百分比输出(这里只做例子,没有真正去做某个工作)。

 

代码1:

  1. import java.awt.FlowLayout;
  2. import java.awt.event.ActionEvent;
  3. import java.awt.event.ActionListener;
  4. import javax.swing.JButton;
  5. import javax.swing.JFrame;
  6. import javax.swing.JProgressBar;
  7. import javax.swing.JTextField;
  8. public class SwingThreadTest1 extends JFrame {
  9. private static final long serialVersionUID = 1L;
  10. private static final String STR = "Completed : ";
  11. private JProgressBar progressBar = new JProgressBar();
  12. private JTextField text = new JTextField(10);
  13. private JButton start = new JButton("Start");
  14. private JButton end = new JButton("End");
  15. private boolean flag = false;
  16. private int count = 0;
  17. public SwingThreadTest1() {
  18. this.setLayout(new FlowLayout());
  19. add(progressBar);
  20. text.setEditable(false);
  21. add(text);
  22. add(start);
  23. add(end);
  24. start.addActionListener(new Start());
  25. end.addActionListener(new End());
  26. }
  27. private void go() {
  28. while (count < 100) {
  29. try {
  30. Thread.sleep(100);//这里比作要完成的某个耗时的工作
  31. } catch (InterruptedException e) {
  32. e.printStackTrace();
  33. }
  34. //更新进度条和输入框
  35. if (flag) {
  36. count++;
  37. progressBar.setValue(count);
  38. text.setText(STR + String.valueOf(count) + "%");
  39. }
  40. }
  41. }
  42. private class Start implements ActionListener {
  43. public void actionPerformed(ActionEvent e) {
  44. flag = true;//设置开始更新的标志
  45. go();//开始工作
  46. }
  47. }
  48. private class End implements ActionListener {
  49. public void actionPerformed(ActionEvent e) {
  50. flag = false;//停止
  51. }
  52. }
  53. public static void main(String[] args) {
  54. SwingThreadTest1 fg = new SwingThreadTest1();
  55. fg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  56. fg.setSize(300, 100);
  57. fg.setVisible(true);
  58. }
  59. }

 

 

运行代码发现,

现象1当点击了开始按钮,画面就卡住了。按钮不能点击,进度条没有被更新,输入框上也没有任何信息。

原因分析:Swing是线程不安全的,是单线程的设计,所以只能从事件派发线程访问将要在屏幕上绘制的Swing组件。ActionListener的actionPerformed方法是在事件派发线程中调用执行的,而点击了开始按钮后,执行了go()方法,在go()里,虽然也去执行了更新组件的方法

progressBar.setValue(count);

text.setText(STR + String.valueOf(count) + "%");

但由于go()方法直到循环结束,它并没有返回,所以更新组件的操作一直没有被执行,这就造成了画面卡住的现象。

现象2过了一段时间(go方法里的循环结束了)后,画面又可以操作,并且进度条被更新,输入框也出现了我们想看到的信息。

原因分析:通过在现象1的分析,很容易联想到,当go()方法返回了,则其他的线程(更新组件)可以被派发了,所以画面上的组件被更新了。

 

 

为了让画面不会卡住,我们来修改代码,将耗时的工作放在一个线程里去做。

 

代码2:

  1. import java.awt.FlowLayout;
  2. import java.awt.event.ActionEvent;
  3. import java.awt.event.ActionListener;
  4. import javax.swing.JButton;
  5. import javax.swing.JFrame;
  6. import javax.swing.JProgressBar;
  7. import javax.swing.JTextField;
  8. public class SwingThreadTest2 extends JFrame {
  9. private static final long serialVersionUID = 1L;
  10. private static final String STR = "Completed : ";
  11. private JProgressBar progressBar = new JProgressBar();
  12. private JTextField text = new JTextField(10);
  13. private JButton start = new JButton("Start");
  14. private JButton end = new JButton("End");
  15. private boolean flag = false;
  16. private int count = 0;
  17. GoThread t = null;
  18. public SwingThreadTest2() {
  19. this.setLayout(new FlowLayout());
  20. add(progressBar);
  21. text.setEditable(false);
  22. add(text);
  23. add(start);
  24. add(end);
  25. start.addActionListener(new Start());
  26. end.addActionListener(new End());
  27. }
  28. private void go() {
  29. while (count < 100) {
  30. try {
  31. Thread.sleep(100);
  32. } catch (InterruptedException e) {
  33. e.printStackTrace();
  34. }
  35. if (flag) {
  36. count++;
  37. System.out.println(count);
  38. progressBar.setValue(count);
  39. text.setText(STR + String.valueOf(count) + "%");
  40. }
  41. }
  42. }
  43. private class Start implements ActionListener {
  44. public void actionPerformed(ActionEvent e) {
  45. flag = true;
  46. if(t == null){
  47. t = new GoThread();
  48. t.start();
  49. }
  50. }
  51. }
  52. //执行复杂工作,然后更新组件的线程
  53. class GoThread extends Thread{
  54. public void run() {
  55. //do something...
  56. go();
  57. }
  58. }
  59. private class End implements ActionListener {
  60. public void actionPerformed(ActionEvent e) {
  61. flag = false;
  62. }
  63. }
  64. public static void main(String[] args) {
  65. SwingThreadTest2 fg = new SwingThreadTest2();
  66. fg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  67. fg.setSize(300, 100);
  68. fg.setVisible(true);
  69. }
  70. }

 

 

我们执行了程序,结果和我们想要的一样,画面不会卡住了。

那这个程序是否没有问题了呢?

我们自定义了一个线程GoThread,在这里我们完成了那些耗时的工作,可以看作是“工作线程”,

而对于组件的更新,我们也放在了“工作线程”里完成了。

在这里,在事件派发线程以外的线程里设置进度条,是一个危险的操作,运行是不正常的。(对于输入框组件的更新是安全的。)

 

只有从事件派发线程才能更新组件,根据这个原则,我们来修改我们现有代码。

 

代码3:

  1. import java.awt.FlowLayout;
  2. import java.awt.event.ActionEvent;
  3. import java.awt.event.ActionListener;
  4. import javax.swing.JButton;
  5. import javax.swing.JFrame;
  6. import javax.swing.JProgressBar;
  7. import javax.swing.JTextField;
  8. import javax.swing.SwingUtilities;
  9. public class SwingThreadTest3 extends JFrame {
  10. private static final long serialVersionUID = 1L;
  11. private static final String STR = "Completed : ";
  12. private JProgressBar progressBar = new JProgressBar();
  13. private JTextField text = new JTextField(10);
  14. private JButton start = new JButton("Start");
  15. private JButton end = new JButton("End");
  16. private boolean flag = false;
  17. private int count = 0;
  18. private GoThread t = null;
  19. private Runnable run = null;//更新组件的线程
  20. public SwingThreadTest3() {
  21. this.setLayout(new FlowLayout());
  22. add(progressBar);
  23. text.setEditable(false);
  24. add(text);
  25. add(start);
  26. add(end);
  27. start.addActionListener(new Start());
  28. end.addActionListener(new End());
  29. run = new Runnable(){//实例化更新组件的线程
  30. public void run() {
  31. progressBar.setValue(count);
  32. text.setText(STR + String.valueOf(count) + "%");
  33. }
  34. };
  35. }
  36. private void go() {
  37. while (count < 100) {
  38. try {
  39. Thread.sleep(100);
  40. } catch (InterruptedException e) {
  41. e.printStackTrace();
  42. }
  43. if (flag) {
  44. count++;
  45. SwingUtilities.invokeLater(run);//将对象排到事件派发线程的队列中
  46. }
  47. }
  48. }
  49. private class Start implements ActionListener {
  50. public void actionPerformed(ActionEvent e) {
  51. flag = true;
  52. if(t == null){
  53. t = new GoThread();
  54. t.start();
  55. }
  56. }
  57. }
  58. class GoThread extends Thread{
  59. public void run() {
  60. //do something...
  61. go();
  62. }
  63. }
  64. private class End implements ActionListener {
  65. public void actionPerformed(ActionEvent e) {
  66. flag = false;
  67. }
  68. }
  69. public static void main(String[] args) {
  70. SwingThreadTest3 fg = new SwingThreadTest3();
  71. fg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  72. fg.setSize(300, 100);
  73. fg.setVisible(true);
  74. }
  75. }

 

 

解释:SwingUtilities.invokeLater()方法使事件派发线程上的可运行对象排队。当可运行对象排在事件派发队列的队首时,就调用其run方法。其效果是允许事件派发线程调用另一个线程中的任意一个代码块。

还有一个方法SwingUtilities.invokeAndWait()方法,它也可以使事件派发线程上的可运行对象排队。

他们的不同之处在于:SwingUtilities.invokeLater()在把可运行的对象放入队列后就返回,而SwingUtilities.invokeAndWait()一直等待知道已启动了可运行的run方法才返回。如果一个操作在另外一个操作执行之前必须从一个组件获得信息,则应使用SwingUtilities.invokeAndWait()方法。

 

--------------------------------------------------------------------------------------------

我的对应的解决办法是: 在要生成对象的地方,制造一个独立的线程来执行生成new InternetBrowser("http://www.baidu.com");的操作

解决问题的代码:

ib1.addActionListener(new ActionListener() {
  
  @Override
  public void actionPerformed(ActionEvent e) {
   if(t==null){
    t=new Thread(new Runnable() {
     
     @Override
     public void run() {
      // TODO Auto-generated method stub
      new InternetBrowser("http://www.baidu.com");
     }
    });
    t.start();
   }
  }
 });

posted @ 2013-03-12 17:32  IamThat  阅读(899)  评论(0编辑  收藏  举报