使用线程在Java中实现JComponent闪烁

时间:2014-10-26 23:56:37

标签: multithreading graphics jcomponent

我正在尝试实现一个程序,我希望不同的组件以不同的速度闪烁。我正在使用线程。但它不起作用。 我该如何实现呢。

这是实现runnable

的类中的void run函数
public void run()
{
    try
    {
        while(true)
        {
            Thread.sleep(1000);
            if(isVisible()==true)
            {
                setVisible(false);
            }
            else
            {
                setVisible(true);
            }
            repaint();
        }


    }

    catch(InterruptedException e)
    {

    }   
}

} 这是我调用线程的类(它在主JPanel的paint组件中) -

{
    cars[i]=new Car(color, xLocation, yLocation, speed, type, i, widthController, heightController);
    cars[i].setBounds(widthController+(xLocation*50)+10,  heightController+(yLocation*50)+10, 30, 30);
    add(cars[i]);

    threads[i]=new Thread(cars[i]);
    threads[i].start();
}

cars是一组JComponents,其中void run是其中的一部分。

由于

1 个答案:

答案 0 :(得分:0)

使用Swing,所有影响可见组件的操作都应该在AWT-EventQueue上运行。这是输入/输出操作以及绘图和组件操作的专用线程。我的建议是为你的跑步操作使用挥杆计时器。您进行的重绘调用将调用AWT-EventQueue上的paintCompnent方法。但是,您要在单独的线程上更改可见性状态。这意味着在进行重绘调用时,状态可能已经变为先前的值。

 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import javax.swing.JPanel;
 import javax.swing.Timer;
 //Rest of code above...
     //This will execute the timer every 500 milliseconds
     Timer aTimer = new Timer(500, new ActionListener() {

     @Override
     public void actionPerformed(ActionEvent pE) {
         aComponent.setVisible(!aComponent.isVisible());

     }
    });
    aTimer.start();

另一个选择是在每个线程上添加此调用: //这应该添加到你的帖子里面

SwingUtilities.invokeLater(new Runnable() {

    @Override
    public void run() {
    aComponent.setVisible(!aComponent.isVisible());
    }
});

以下是我在评论中提到的答案:

public void run()
{
    try
    {
        while(true)
        {
            Thread.sleep(1000);
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                setVisible(!isVisible());
            }

        }
    });


    }

    catch(InterruptedException e)
    {

    }