使用线程 ,将一个panel 的背景每200ms改变一次 

解决方案 »

  1.   

    不需要线程,使用TimerTask就行了
    // BKColorPanel.javaimport java.awt.*;
    import java.util.*;
    import javax.swing.*;public class BKColorPanel extends JPanel {
        // 使用TimerTask改变颜色
        class BKChangeTask extends TimerTask{
            JComponent target;        BKChangeTask(JComponent target){
                this.target = target;
            }
            public void run(){
                // 生成随机颜色
                float r = (float)Math.random();
                float g = (float)Math.random();
                float b = (float)Math.random();            // 改变背景颜色
                target.setBackground(new Color(r,g,b));
            }
        }    public BKColorPanel(){
            // 创建timer
            java.util.Timer timer = new java.util.Timer();
            timer.schedule(new BKChangeTask(this), 200, 200);
        }    public static void main(String[] args) {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container container = frame.getContentPane();        container.add(new BKColorPanel(), BorderLayout.CENTER);        frame.setPreferredSize(new Dimension(300, 200));        frame.pack();        Dimension screen = 
                Toolkit.getDefaultToolkit().getScreenSize();
            int x =    (screen.width - frame.getWidth()) / 2;
            int y = (screen.height - frame.getHeight()) / 2;        frame.setLocation(x, y);        frame.setVisible(true);
        }
    }
      

  2.   

    楼上的说得对阿,用Timer就行了
      

  3.   

    换成下面代码就行了。    class BKChangeTask extends Thread{
            public void run(){
                while (true) {
                    // 生成随机颜色
                    float r = (float)Math.random();
                    float g = (float)Math.random();
                    float b = (float)Math.random();                // 改变背景颜色
                    setBackground(new Color(r,g,b));                try {
                        sleep(200);
                    } catch (Exception e) {
                    }
                }
            }
        }    public BKColorPanel1(){
            Thread t = new BKChangeTask();
            t.start();
        }