跑马灯的简单实现

引用

package org.tarena.day01;

import java.awt.BorderLayout;
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.JPanel;
import javax.swing.JTextField;

public class MarqueeFrame {

	
	JTextField text = new JTextField(15);
	JFrame jf= new JFrame("跑马灯");
	JButton bt1 = new JButton("开始");
	JButton bt2 = new JButton("结束");
	public MarqueeFrame(){
		bt1.addActionListener(new ActionListener(){

			public void actionPerformed(ActionEvent e) {
				runStart();
			}
			
		});
		bt2.addActionListener(new ActionListener(){

			public void actionPerformed(ActionEvent e) {
				running = false;
			}
			
		});
		JPanel jp = new JPanel(new FlowLayout());
		jp.add(text);
		jp.add(bt1);
		jp.add(bt2);
		
		jf.add(jp,BorderLayout.NORTH);
		jf.setSize(350,100);
		//jf.pack();
		jf.setLocation(400, 500);
		jf.setVisible(true);
		jf.setResizable(false);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
	}
	
	static boolean running = false;
	public void runStart(){
		if(running) return;// 正在跑,无须再创建线程
		running = true;
		new Thread(){
			public void run(){	
				while(running){// 停止按钮按下时会将running设为false
					String s = text.getText();
					String str1 = s.substring(0,1);
					String str2 = s.substring(1);
					s = str2 + str1;
					text.setText(s);
					try {
						Thread.sleep(300);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}						
				}
			}			
		}.start();
		
	}
	public static void main(String[] args) {
		new MarqueeFrame();
	}

}


你可能感兴趣的:(java,thread,swing)