在 window 中循环遍历颜色

Looping through colours in a window

我是 Java 编程的初学者,遇到了一个问题(可能很容易解决)。

我正在试验 Java GUI,并希望创建一个 window,其中数组的颜色会循环显示,直到没有更多颜色为止。我相信我可以使用 for 循环并循环遍历数组来做到这一点,但是我不知道如何遍历背景颜色。

如有任何帮助和解释,我们将不胜感激。

public void flashColor()  { 

    Color [] color = { Color.red,Color.orange,Color.green };

    int i = 0;
    for(i=0;i<color.length;i--){

        getContentPane().setBackground(Color(i));
    }
}

这一行告诉我:

getContentPane().setBackground(Color(i));

您的似乎是 Swing GUI(您在问题中遗漏的关键信息!),因此您需要考虑 Swing 线程。您当前的代码实际上将遍历所有颜色,但它会立即在 Swing 线程上这样做,这样 GUI 将无法绘制除最后一种颜色之外的任何颜色。解决方案:使用 Swing Timer 而不是 for 循环。在计时器内部推进一个索引 int 变量并用它来显示颜色。

类似于:

getContentPane().setBackground(colorArray[0]);
int delay = 1000; // for 1 second
Timer myTimer = new Timer(delay, new ActionListener() {

    int index = 0;
    public void actionPerformed(ActionEvent e) {
       index++;
       if (index >= colorArray.length) {
          ((Timer)e.getSource()).stop(); // stop the timer
       } else {
          getContentPane().setBackground(colorArray[index]);
       }
    }

});
myTimer.start();

代码尚未经过测试,您需要阅读 Swing Timer 教程以了解详细信息。

注意这里的关键是,是的,你需要循环,并暂停(以便可以看到颜色)但是你需要在一个thread 线程脱离了 Swing 事件调度线程(或 EDT)。是的,您可以使用 SwingWorker 来执行此操作,但这是一种更难执行此操作的方法。 使用 Swing Timer 为您做这件事要容易得多。请注意,它为您使用了一个不可见的后台线程。