线程之画不同颜色的线

来源:互联网 发布:网络平台代理协议 编辑:程序博客网 时间:2024/06/05 00:13
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;


import javax.swing.JFrame;


public class ThreadList extends JFrame {
Thread t;
private static Color[] color={Color.BLACK,Color.BLUE,Color.CYAN,Color.GREEN,Color.ORANGE,Color.YELLOW,Color.RED,Color.PINK};
private static final Random rand=new Random();//声明随机对象
private static Color getC(){//获取随机颜色的方法
return color[rand.nextInt(color.length)];//颜色的长度随机
}
public ThreadList(){//构造方法
t=new Thread(new Runnable(){
int x=30;
int y=50;
public void run(){
while(true){
try{
t.sleep(100);
}catch(Exception e){
e.printStackTrace();
}
Graphics graphics=getGraphics();//获取组件绘图
graphics.setColor(getC());//设置绘图颜色
graphics.drawLine(x,y,100,y++);//y坐标加
if(y>80){
y=50;
}

}
}
});
t.start();
}
 
public static void main(String[] args){
init(new ThreadList(),100,100);
}
public static void init(JFrame frame,int width,int height){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width,height);
frame.setVisible(true);
}
}
原创粉丝点击