JButton 的颜色转换

Color Transition of a JButton

我试图让一个 JButton 经历颜色转换,所以我向它添加了一个动作侦听器,它执行以下操作:

public void actionPerformed(ActionEvent arg0) {
    Color c = new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256));
    Color cc = v.get(1).getBackground();
    //(...) The r, rr, b, bb, g, gg are just the components of the colors c and cc
    boolean boo = true;
    while(boo){
        if(r < rr){
            r++;
        }
        if(b < bb){
            b++;
        }
        if(g < gg){
            g++;
        }
        if(r == rr && b == bb && g == gg){
            boo = false;
        }
        Color color = new Color(r, b, g);
        v.get(1).setBackground(color);
        v.get(0).setBackground(color);
        frame.repaint();
        frame.revalidate();
    }

但这并没有使转换发生,它实际上只是改变了按钮的颜色。我在这里错过了什么?

您需要使用另一个线程来执行此逻辑并在操作发生时启动该线程。长操作会阻塞负责图形更改的线程。

因此,您的问题是您打算实时完成每个图形更改,而不是使用单独的线程异步工作,而是同步工作,在事件函数完成时释放 EDT。