饿,当点击一个按钮触发事件,而这个事件里连接数据库呀,什么的一大堆,而导致界面有一段时间死掉不能动,这是swing的常见问题,请问各位大大用什么方法可以解决,最好可以给出代码来看看

解决方案 »

  1.   

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    /**
     * 没有使用线程的按钮将会在全部运算完成后给出一个最终的结果,而使用了线程的按钮将会把运算过程都现实出来
     */public class Test extends JFrame { private static final long serialVersionUID = -2397593626990759111L;
    private JPanel pane = null; private JButton b_1 = null, b_2 = null; private JLabel label = null; public Test() {
    super("Test");
    pane = new JPanel();
    label = new JLabel();
    b_1 = new JButton("按钮没使用线程");
    b_2 = new JButton("使用线程的按钮");
    b_1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
    for (int i = 0; i < 100; i++) {
    label.setText("显示运算过程: " + (i + 1));
    try {
    Thread.sleep(100);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    });
    b_2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    ThreadLabel tl = new ThreadLabel();
    tl.start();
    }
    });
    pane.add(b_1);
    pane.add(b_2);
    pane.add(label);
    this.getContentPane().add(pane);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(300, 200);
    this.setLocationRelativeTo(null);
    this.setVisible(true);
    } public static void main(String args[]) {
    new Test();
    } class ThreadLabel extends Thread {
    public void run() {
    for (int i = 0; i < 100; i++) {
    label.setText("显示运算过程: " + (i + 1));
    try {
    Thread.sleep(100);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }}
      

  2.   

    开个新的线程来执行    
     doButton.addActionListener(new
             ActionListener()
             {
                public void actionPerformed(ActionEvent event)
                {
                  Thread thread=new Thread(new Runnable()
                                {
                                    public void run()
                                    {
                                   原先的执行代码COPY过来
                                      }
                                });
                  thread.start();
                }
             });
      

  3.   

    我有篇博客详细介绍了Swing线程编程解决这类问题:
    http://blog.sina.com.cn/u/4b6047bc010007ks
    不妨看一下。
      

  4.   

    其实不只是按钮事件
    几乎所有的Listener都这样,大的操作放到线程里去做