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:
- import java.awt.FlowLayout;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JProgressBar;
- import javax.swing.JTextField;
- public class SwingThreadTest1 extends JFrame {
- private static final long serialVersionUID = 1L;
- private static final String STR = "Completed : ";
- private JProgressBar progressBar = new JProgressBar();
- private JTextField text = new JTextField(10);
- private JButton start = new JButton("Start");
- private JButton end = new JButton("End");
- private boolean flag = false;
- private int count = 0;
- public SwingThreadTest1() {
- this.setLayout(new FlowLayout());
- add(progressBar);
- text.setEditable(false);
- add(text);
- add(start);
- add(end);
- start.addActionListener(new Start());
- end.addActionListener(new End());
- }
- private void go() {
- while (count < 100) {
- try {
- Thread.sleep(100);//这里比作要完成的某个耗时的工作
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- //更新进度条和输入框
- if (flag) {
- count++;
- progressBar.setValue(count);
- text.setText(STR + String.valueOf(count) + "%");
- }
- }
- }
- private class Start implements ActionListener {
- public void actionPerformed(ActionEvent e) {
- flag = true;//设置开始更新的标志
- go();//开始工作
- }
- }
- private class End implements ActionListener {
- public void actionPerformed(ActionEvent e) {
- flag = false;//停止
- }
- }
- public static void main(String[] args) {
- SwingThreadTest1 fg = new SwingThreadTest1();
- fg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- fg.setSize(300, 100);
- fg.setVisible(true);
- }
- }
运行代码发现,
现象1:当点击了开始按钮,画面就卡住了。按钮不能点击,进度条没有被更新,输入框上也没有任何信息。
原因分析:Swing是线程不安全的,是单线程的设计,所以只能从事件派发线程访问将要在屏幕上绘制的Swing组件。ActionListener的actionPerformed方法是在事件派发线程中调用执行的,而点击了开始按钮后,执行了go()方法,在go()里,虽然也去执行了更新组件的方法
progressBar.setValue(count);
text.setText(STR + String.valueOf(count) + "%");
但由于go()方法直到循环结束,它并没有返回,所以更新组件的操作一直没有被执行,这就造成了画面卡住的现象。
现象2:过了一段时间(go方法里的循环结束了)后,画面又可以操作,并且进度条被更新,输入框也出现了我们想看到的信息。
原因分析:通过在现象1的分析,很容易联想到,当go()方法返回了,则其他的线程(更新组件)可以被派发了,所以画面上的组件被更新了。
为了让画面不会卡住,我们来修改代码,将耗时的工作放在一个线程里去做。
代码2:
- import java.awt.FlowLayout;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JProgressBar;
- import javax.swing.JTextField;
- public class SwingThreadTest2 extends JFrame {
- private static final long serialVersionUID = 1L;
- private static final String STR = "Completed : ";
- private JProgressBar progressBar = new JProgressBar();
- private JTextField text = new JTextField(10);
- private JButton start = new JButton("Start");
- private JButton end = new JButton("End");
- private boolean flag = false;
- private int count = 0;
- GoThread t = null;
- public SwingThreadTest2() {
- this.setLayout(new FlowLayout());
- add(progressBar);
- text.setEditable(false);
- add(text);
- add(start);
- add(end);
- start.addActionListener(new Start());
- end.addActionListener(new End());
- }
- private void go() {
- while (count < 100) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- if (flag) {
- count++;
- System.out.println(count);
- progressBar.setValue(count);
- text.setText(STR + String.valueOf(count) + "%");
- }
- }
- }
- private class Start implements ActionListener {
- public void actionPerformed(ActionEvent e) {
- flag = true;
- if(t == null){
- t = new GoThread();
- t.start();
- }
- }
- }
- //执行复杂工作,然后更新组件的线程
- class GoThread extends Thread{
- public void run() {
- //do something...
- go();
- }
- }
- private class End implements ActionListener {
- public void actionPerformed(ActionEvent e) {
- flag = false;
- }
- }
- public static void main(String[] args) {
- SwingThreadTest2 fg = new SwingThreadTest2();
- fg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- fg.setSize(300, 100);
- fg.setVisible(true);
- }
- }
我们执行了程序,结果和我们想要的一样,画面不会卡住了。
那这个程序是否没有问题了呢?
我们自定义了一个线程GoThread,在这里我们完成了那些耗时的工作,可以看作是“工作线程”,
而对于组件的更新,我们也放在了“工作线程”里完成了。
在这里,在事件派发线程以外的线程里设置进度条,是一个危险的操作,运行是不正常的。(对于输入框组件的更新是安全的。)
只有从事件派发线程才能更新组件,根据这个原则,我们来修改我们现有代码。
代码3:
- import java.awt.FlowLayout;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JProgressBar;
- import javax.swing.JTextField;
- import javax.swing.SwingUtilities;
- public class SwingThreadTest3 extends JFrame {
- private static final long serialVersionUID = 1L;
- private static final String STR = "Completed : ";
- private JProgressBar progressBar = new JProgressBar();
- private JTextField text = new JTextField(10);
- private JButton start = new JButton("Start");
- private JButton end = new JButton("End");
- private boolean flag = false;
- private int count = 0;
- private GoThread t = null;
- private Runnable run = null;//更新组件的线程
- public SwingThreadTest3() {
- this.setLayout(new FlowLayout());
- add(progressBar);
- text.setEditable(false);
- add(text);
- add(start);
- add(end);
- start.addActionListener(new Start());
- end.addActionListener(new End());
- run = new Runnable(){//实例化更新组件的线程
- public void run() {
- progressBar.setValue(count);
- text.setText(STR + String.valueOf(count) + "%");
- }
- };
- }
- private void go() {
- while (count < 100) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- if (flag) {
- count++;
- SwingUtilities.invokeLater(run);//将对象排到事件派发线程的队列中
- }
- }
- }
- private class Start implements ActionListener {
- public void actionPerformed(ActionEvent e) {
- flag = true;
- if(t == null){
- t = new GoThread();
- t.start();
- }
- }
- }
- class GoThread extends Thread{
- public void run() {
- //do something...
- go();
- }
- }
- private class End implements ActionListener {
- public void actionPerformed(ActionEvent e) {
- flag = false;
- }
- }
- public static void main(String[] args) {
- SwingThreadTest3 fg = new SwingThreadTest3();
- fg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- fg.setSize(300, 100);
- fg.setVisible(true);
- }
- }
解释: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();
}
}
});