JAVA之多线程入门和自动滚轮

JAVA之多线程入门和自动滚轮_第1张图片

start实现每1s递增的在textarea打印一个数字,end实现终止start的线程


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.Random;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;

public class test extends JFrame{
	JTextArea jt = new JTextArea(10,10);
	JButton jb_s = new JButton("start!");
	JButton jb_e = new JButton("end!");
	JScrollPane js = new JScrollPane(jt);
	Thread t1 ,t2;
	int count  = 0;
	boolean flag = true;
	
	public test(){
		init();
		
		jb_s.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				flag = true;
				jt.setLineWrap(true);
				jt.setEditable(false);
				t1 = new Thread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						while(flag){
							jt.append(count++ + " \n");//
							jt.setCaretPosition(jt.getText().length());//方法1:自动滚动到textarea的底部
							//js.getViewport().setViewPosition(new Point(0,jt.getLineCount()*20));//方法2
							try {
								Thread.sleep(100);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
				
						}
					}
				});
				t1.start();
			}
		});
		
		jb_e.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				t2 = new Thread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
							flag = false;
					}
				});
				
				t2.start();
			}
		});
	}
	
	public void init(){
		setLocationRelativeTo(null);
		Container con = getContentPane();
		con.add(js,BorderLayout.NORTH);
		
		JPanel jp = new JPanel();
		jp.setLayout(new FlowLayout());
		jp.add(jb_s);
		jp.add(jb_e);
		jp.setOpaque(false);
		con.add(jp,BorderLayout.SOUTH);
		
		setVisible(true);
		setSize(500,300);
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
	}
	
	public static void main(String[] agrs){
		new test();
	}
}


你可能感兴趣的:(JAVA)