Java Swing与线程的结合应用(三)

package com.han;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics2D;
import java.util.Random;

import javax.swing.JFrame;

/**
 * 利用线程在Swing窗口(顶级Container, 与JFrame有区别在于多了标题栏的空间)中画动态线条
 * 
 * @author HAN
 * 
 */
public class ThreadAndSwing_3 extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -913556444768132509L;

	static Thread thread;
	Container container;

	enum Colors {
		BLACK(Color.BLACK),
		BLUE(Color.BLUE),
		CYAN(Color.CYAN),
		GREEN(Color.GREEN), 
		ORANGE(Color.ORANGE),
		YELLOW(Color.YELLOW), 
		RED(Color.RED), 
		PINK(Color.PINK), 
		LIGHT_GRAY(Color.LIGHT_GRAY);

		private Color c;

		private Colors(Color c) {
			this.c = c;
		}

		public Color getColor() {
			return this.c;
		}
	}

	public ThreadAndSwing_3() {
		// TODO Auto-generated constructor stub
		container = getContentPane();
		container.setLayout(null);
	}

	void paintJFrame() {
		thread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				/*
				 * Creates a graphics context for Container (you can also try it
				 * for JFrame)
				 */
				Graphics2D g = (Graphics2D) container.getGraphics();

				Colors[] colors = Colors.values();
				Random random = new Random();
				int y2 = 30;
				float width = 0;

				while (true) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					/*
					 * Returns a pseudorandom, uniformly distributed int value
					 * between 0 (inclusive) and the specified value (exclusive)
					 */
					Color c = colors[random.nextInt(colors.length)].getColor();
					// System.out.println(c);

					g.setColor(c);
					g.setStroke(new BasicStroke(width++));

					/*
					 * Draws a line, using the current color, between the points
					 * (x1, y1) and (x2, y2) in this graphics context's
					 * coordinate system.
					 */
					g.drawLine(30, y2, 100, y2++);

					if (y2 > 70) {
						width = 0;
						y2 = 30;
					}

				}

			}

		});
		thread.start();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ThreadAndSwing_3 frame = new ThreadAndSwing_3();
		frame.setTitle("利用线程在Swing窗口中画动态线条");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setBounds(100, 100, 300, 200);
		frame.setVisible(true); // display the frame

		/*
		 * because g will be null if Graphics g = container.getGraphics();
		 * before the display of the related component
		 */
		frame.paintJFrame();
	}

}


你可能感兴趣的:(Java Swing与线程的结合应用(三))