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();
	}

}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值