java制作霓虹灯_Java 线程编码之霓虹灯的实现

Java线程的实现通常要继承Thread类或者是实现接口Runnable的run方法即可。

实现代码如下:

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();

}

}

运行结果如下:

512db878dd84c09d9e6765ede760647b.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值