JAVA多线程编程求教

编写一个可变颜色的标签,用一个按钮控制颜色的改变与停止。点击按钮颜色停止变化,再点击该按钮颜色又变化。颜色的变化可用随机数确定。
先谢谢一L了

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

}
}
//有注释了.
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-12-11
代码就不给了,给你个思路,用一个线程刷新标签的颜色,再设置一个变量判断是否执行(比如boolean run=true),点击按钮后变量设置run为false,再点一下又变回true,这样就可以了,思路有了应该好做了,楼主加油
第2个回答  2009-12-08
public class A {

public static void main(String[] args) throws FileNotFoundException, IOException {
JFrame frame = new JFrame();
final JButton button = new JButton("123");
final javax.swing.Timer timer = new Timer(500, new AbstractAction() {

public void actionPerformed(ActionEvent e) {
button.setBackground(new Color((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255)));
}
});
button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
if (timer.isRunning()) {
timer.stop();
} else {
timer.start();
}
}
});
timer.setRepeats(true);
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(3);
frame.setVisible(true);
}
}
第3个回答  2009-12-08
不难吧,貌似跟多线程也没有关系.没有现成的程序.有时间帮你做做.不过现在很忙.