Java Swing与线程的结合应用(三)
2012-07-21 02:37
387 查看
![](http://my.csdn.net/uploads/201207/21/1342809954_6157.png)
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与线程的结合应用(一)
- Java Swing与线程的结合应用(一)
- Java Swing与线程的结合应用(二)
- Java Swing与线程的结合应用(二)
- Java Swing与线程的结合应用(三)
- 结合Java实现的一个腾讯空间备份器谈谈MVC思想在Swing桌面项目中的应用
- JAVA——Swing应用编写简单的记事本——源代码分析实战(一)
- Java线程及多线程技术及应用(一)
- java swing应用(1):画一个眨眼珠的笑脸
- java笔记--守护线程的应用
- 线程高级应用-心得5-java5线程并发库中Lock和Condition实现线程同步通讯
- Java开发中的线程安全选择与Swing
- 反射在Java Swing中的应用
- JAVA基础之Swing基础应用
- Java回调以及线程综合应用实例--陆续添加
- Java线程的高级应用
- java 线程、线程池基本应用演示样例代码回想
- 8-java5线程并发库的应用
- 反射在Java Swing中的应用
- java工厂模式应用——多数据库分页实现(结合Spring)