java 多线程在swing中的应用

在Swing中进行界面设计的时候,如果点击一个耗时的按钮会发现,在这个按钮的监听方法没返回时,是无法按其它按钮的,多线程能很好的解决这个问题.


package test1;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ThreadFrame extends JFrame{

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ThreadFrame tf = new ThreadFrame();
		tf.setVisible(true);
	}
	
	private JButton btn_login;
	private JButton btn_register;
	private JPanel panel;
	public ThreadFrame(){
		
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setBounds(100, 100, 200, 300);
		btn_login = new JButton("登陆");
		btn_register = new JButton("注册");
		panel = new JPanel();
		setContentPane(panel);
		panel.add(btn_login);
		panel.add(btn_register);
		
		class ActionImp implements Runnable{
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				System.out.println(Thread.currentThread().getName()+ "正在注册");
				try {
					Thread.sleep(7000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("注册完毕");
			}
		}
		
		btn_register.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				new Thread(new ActionImp()).start();
			}
		});
		
		btn_login.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				System.out.println("正在登陆");
			}
		});
		
		/*btn_register.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				try {
					System.out.println("正在注册");
					Thread.sleep(7000);
					System.out.println("注册完毕");
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});*/
	}
}



你可能感兴趣的:(Java基础知识)