`
happyqing
  • 浏览: 3153851 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

使用多线程技术让你的Swing及时响应各类事件

阅读更多

 

在执行时间长点的任务是,主窗体不响应事件,这是因为你执行任务的线程是窗体的主线程,所有不能及时响应,应开新的线程里执行大任务。

 

使用线程例子

package com.urt.module;

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
//import com.borland.jbcl.layout.*;

/**
 * Title: Description: Copyright: Copyright (c) 2002 Company:
 *
 * @author
 * @version 1.0
 */
public class TestThread extends JFrame {

    JPanel jPanel1 = new JPanel();
    //XYLayout xYLayout1 = new XYLayout();
    JButton startButton = new JButton();
    JButton stopButton = new JButton();
    MyThread thread = null;

    public TestThread() {
        try {
            jbInit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void jbInit() throws Exception {
        //jPanel1.setLayout(xYLayout1);
        startButton.setText("start");
        startButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                startButton_actionPerformed(e);
            }
        });
        stopButton.setText("stop");
        stopButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                stopButton_actionPerformed(e);
            }
        });
        this.getContentPane().add(jPanel1, BorderLayout.CENTER);
        jPanel1.add(startButton);
        jPanel1.add(stopButton);
    }

    void startButton_actionPerformed(ActionEvent e) {
        if (thread != null) {
            thread.stop();
        }
        thread = new MyThread();
        thread.start();
    }

    void stopButton_actionPerformed(ActionEvent e) {
        if (thread != null) {
            thread.stop();
        }
        thread = null;
    }

    public static void main(String[] args) {
        TestThread test = new TestThread();
        test.setSize(300, 400);
        test.show();
    }

    private class MyThread extends Thread {

        public MyThread() {
        }

        public void run() {
            while (true) {
                try {
                    sleep(100);
                } catch (InterruptedException e) {
                }
                System.out.println("this is a test!");
            }
        }
    }
}

 

简单的写法

private void btnCompareActionPerformed(java.awt.event.ActionEvent evt) {
        new Thread() {
            public void run() {
                //在这写代码,可以把逻辑写在另一个类里
                //strOriginal
            }
        }.start();
}

 

在这也可以直接掉用另一个线程类去执行,记得调用是start(),不要调用run(),否则主窗体事件还是不能及时响应。

 

用Swing编写灵敏的图形用户界面

http://java.chinaitlab.com/Swing/23050.html

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics