如何使用 setForeground 使用 JFrame、JLabel 创建颜色模拟?

How can i Create Color simulation with JFrame, JLabel, using setForeground?

我真的怀疑这是最好的方法,但这是我目前正在使用的方法。我在 JPanel 中有这 3 个 JLabel 对象。所以 3 个圆圈位于字体 99 的 JPanel 中。从左到右,圆圈的颜色为 R B G.The \u2022 是一个圆圈。

残局目标:能够将圆圈从打开变为关闭。所以说默认开始是白色的。我希望能够做到 |R W W|或 |W B G |。但我遇到的问题是,我希望用户能够看到颜色的变化,这就是重点。我试过等待,但它只是冻结了程序,然后它产生了颜色,没有过渡。我知道它会立即改变,但我想暂停它几毫秒或半秒,以便用户可以看到它们打开和关闭。

示例:第二个 1 传球,|R W W|第二个 2 |W W W|第二个 3 |R B W|第二个 4 |W W W|第二个 5 |R W G|....等等

    ballR = new JLabel("\u2022");
    panel.add(ballR);
    ballR.setForeground(Color.RED);
    ballR.setFont(new Font("Tahoma", Font.PLAIN, 99));

^^ 我每个颜色都有一个,红的,蓝的,绿的^^

    private void colorRed(){

    ballR.setForeground(Color.RED);

    try {
        TimeUnit.SECONDS.sleep((1);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ballR.setForeground(Color.WHITE);

}

I tried Wait, but it just froze the program and then it yielded the color, without transition

目前尚不清楚您是否在 EDT 上调用此代码,但从描述来看是这样的 - 在 EDT 上休眠(或执行长时间的 运行 任务)使用将防止任何重绘或从触发到方法 returns 的监听​​器(换句话说,UI 锁定)。

but i want to pause it for a few miliseconds, or half a second so the user can see them go on and off.

如果您希望在指定时间(或重复时间间隔)后在 EDT 上执行任务,请使用 Timer

Timer timer = new Timer(500, new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e){
        ballR.setForeground(Color.WHITE);//or RED, depending
    }
});
timer.setRepeats(false);//don't repeat if you don't want to
timer.start();