JButton的颜色过渡

时间:2016-04-12 13:51:03

标签: java swing 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();
    }

但是这不会使转换发生,它实际上只是改变了Button的颜色。我在这里错过了什么?

1 个答案:

答案 0 :(得分:2)

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

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