package com;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ColorThread
{
public static void main(String[] args)
{
Myframe mf =new Myframe();//实例化对象
Thread t=new Thread(mf);//加入线程
t.start();//启动线程
}
}
class Myframe extends JFrame implements Runnable,ActionListener
{
private static final long serialVersionUID = 1L;
Random rand = new Random(System.currentTimeMillis());//随机数.用当前系统时间做基数
JPanel panel = new JPanel();//变色的面板
final JButton button = new JButton("点击停止或启动");//按钮
int action=0;//变色或停止变色 判断标示
public Myframe()
{
super("1/10秒变色1次");
button.setBounds(10, 10, 200, 30); //设置按钮坐标
button.addActionListener(this); //设置按钮监听
panel.setBounds(10, 50, 100, 100); //面板坐标
panel.setBackground(Color.BLUE); //面板初始颜色
this.setBounds(100, 100, 300, 300); //frame 初始大小坐标
this.add(panel); //将面板加入frame
this.setLayout(null); //设置frame布局为null
this.add(button); //将按钮加入frame
this.setDefaultCloseOperation(3); //设置关闭frame就退出程序
this.setVisible(true); //设置frame显示为可见
}
/**
* 实现Runnable线程接口
*/
public void run()
{
while (true)//设置死循环
{
try
{
if(action==0)//判断操作为0时改变面板背景颜色
{
panel.setBackground(getcolor()); //变色
}
Thread.sleep(100);//10之一秒 的休眠
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
private Color getcolor() //获得颜色
{
return new Color(getNum(), getNum(), getNum());
}
private int getNum() //获得小于255的随机数字
{
return rand.nextInt(255);
}
public void actionPerformed(ActionEvent e)//监听事件
{
if(action==0) //点击后判断.修改值.
{
action =1;
}else
{
action =0;
}
}
}
//有注释了.
温馨提示:答案为网友推荐,仅供参考