我真的怀疑这是最好的方法,但这就是我目前正在使用的方法。我在 JPanel 中有这 3 个 JLabel 对象。因此,JPanel 中的字体为 99,有 3 个圆圈。从左到右,圆圈的颜色为 R B G。\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 上 hibernate (或执行长时间运行的任务)使用将阻止任何重绘或监听器触发,直到该方法返回(换句话说,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();
关于java - 如何使用 JFrame、JLabel、使用 setForeground 创建颜色模拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30248789/