实现代码如下:
package com.Android.test;
import java.awt.Color;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class NeonLight extends JFrame{
private static final long serialVersionUID = 5246470000332954366L;
public JLabel[] label = {new JLabel("TAG-1"),
new JLabel("TAG-2"),
new JLabel("TAG-3"),
new JLabel("TAG-4"),
new JLabel("TAG-5"),
new JLabel("TAG-6"),
new JLabel("TAG-7")};
public Color[] color = {Color.BLACK,
Color.BLUE,
Color.YELLOW,
Color.GRAY,
Color.PINK,
Color.GREEN,
Color.ORANGE,
Color.RED};
public NeonLight() {
// TODO Auto-generated constructor stub
setSize(500, 800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setLayout(new FlowLayout());
setLayout(null);
getContentPane().add(label[0]);
label[0].setBounds(0,5,500,100);
//设置组件JLabel不透明,只有设置为不透明,设置背景色才有效
label[0].setOpaque(true);
getContentPane().add(label[1]);
label[1].setBounds(0,5+100,500,100);
label[1].setOpaque(true);
getContentPane().add(label[2]);
label[2].setBounds(0,5+200,500,100);
label[2].setOpaque(true);
getContentPane().add(label[3]);
label[3].setBounds(0,5+300,500,100);
label[3].setOpaque(true);
getContentPane().add(label[4]);
label[4].setBounds(0,5+400,500,100);
label[4].setOpaque(true);
getContentPane().add(label[5]);
label[5].setBounds(0,5+500,500,100);
label[5].setOpaque(true);
getContentPane().add(label[6]);
label[6].setBounds(0,5+600,500,100);
label[6].setOpaque(true);
setVisible(true);
}
//通过内部类实现霓虹灯任务类
class ColorVariance implements Runnable{
public void run() {
while (true) {
try {
// 设置灯闪烁的频率
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
for (int i = 0; i < label.length; i++) {
// 随机设置背景颜色
label[i].setBackground(color[new Random().nextInt(7)]);
}
}
}
}
public static void main(String [] args){
NeonLight neonL = new NeonLight();
// 创建线程,注入霓虹灯任务
Thread ted = new Thread(neonL.new ColorVariance() );
// 开始闪烁
ted.start();
}
}
运行结果如下: