package com.suse.thread;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
public class SleepMethodTest extends JFrame {
private Thread t;
//定义数组颜色
private static Color[] color={
Color.BLACK,Color.BLUE,Color.CYAN,
Color.GREEN,Color.ORANGE,Color.YELLOW,Color.RED,
Color.PINK,Color.LIGHT_GRAY
};
private static Random rand=new Random();//获取随机颜色值的方法
private static Color getC(){
return color[rand.nextInt(color.length)];//math.random产生的区间是左闭右开,而数组下标刚刚是(0,length-1)
}
public SleepMethodTest(){
t=new Thread(new Runnable(){
int x=30;
int y=50;
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//获取组件绘图上下文对象
Graphics graphics=getGraphics();
graphics.setColor(getC());
//绘制直线并递垂直增
graphics.drawLine(x, y, 100, y++);
if(y>=80){
y=50;
}
}
}
});
t.start();
}
//初始化程序界面的方法
public static void init(JFrame frame,int width,int height){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width, height);
frame.setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
init(new SleepMethodTest(),100,100);
}
}
线程控制实现彩色线条绘制
最新推荐文章于 2021-07-26 14:59:43 发布