编写一个可变颜色的标签,用一个按钮控制颜色的改变与停止.点击按钮颜色停止变化,

编写一个可变颜色的标签,用一个按钮控制颜色的改变与停止.点击按钮颜色停止变化,


import
java.awt.Button;

import
java.awt.Color;

import
java.awt.FlowLayout;

import
java.awt.Frame;

import
java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import
java.awt.event.WindowAdapter;

import
java.awt.event.WindowEvent;import
java.awt.Label;

import
java.util.Random;

public class ChangeColor extends Frame implements ActionListener{ 

 

    Label l = new Label(" 变色区域 ");

    Button b = new Button("开始");

    boolean flag = false;

public static void main(String[] args) {

 

    ChangeColor cc = new ChangeColor();

    }

        public ChangeColor(){

        this.setBounds(400, 300, 200, 100);

        this.addWindowListener(new WindowAdapter(){ @Override

            public void windowClosing(WindowEvent arg0) {

            //super.windowClosing(arg0);

            System.exit(0);

}

});

        this.setTitle("变色器");

        this.setLayout(new FlowLayout());

        this.add(l);

        this.add(b);

        b.addActionListener(this);

        Inner inner = new Inner();

        inner.start();

        this.setVisible(true);

}

 

public void actionPerformed(ActionEvent e) {

 

    if(e.getActionCommand().equals("开始")){

        flag = true;

        b.setLabel("停止");

    }else if(e.getActionCommand().equals("停止")){

        flag = false;

        b.setLabel("开始");

    }

}

class Inner extends Thread{

    Random rd = new Random();

    public void run() {

        while(true){

            while(flag){

                l.setBackground(new Color(rd.nextInt(256),rd.nextInt(256),rd.nextInt(256)));

                try {

                    Thread.sleep(1000);

                } catch (InterruptedException e) {

                        e.printStackTrace();

                }   

            }

            try {

                Thread.sleep(1000);

            } catch (InterruptedException e) {

                e.printStackTrace();

                }

            }

        }

    }

}


你可能感兴趣的:(编写一个可变颜色的标签,用一个按钮控制颜色的改变与停止.点击按钮颜色停止变化,)