user234234234
user234234234

Reputation: 97

Threaded JLabel with changing icon atop another changing icon

I've already created a JLabel who's image changes back and forth between two frames like this.

private class CustomLabel extends JLabel implements Runnable
{       
    ImageIcon car1=new ImageIcon(/*icon*/);//makes the wave equal to the wave in outer class (passing reference)
    ImageIcon car2=new ImageIcon(/*icon*/);
    ImageIcon currentCar;
    int current=0;


    public CustomLabel()
    {
        if(x>0 && y<11)setIcon(wave1);

        new Thread(this).start();//am i starting this right?
    }

    @Override
    public void run()
    {
       while (true) 
       {
        if(current == 0)
        {
        setIcon(wave1); 
        current++;
        }
        else
        {
         setIcon(wave2);
         current--;
        }
        repaint();
        try { Thread.sleep(150); }
        catch (InterruptedException e) { }
       }
   }
}

So when i add this JLabel it will alternate between two car pictures. Firstly am I starting the thread correctly by starting it in the constructor?

Now let's say I want there to be a another animation on top of the cars that that is a 5 framed explosion animation that happens when I click the JLabel. How do I go about overlaying the second threaded animation on a current animation. I feel like I need to override the paintComponent() but I'm not too sure how to do that.

Upvotes: 0

Views: 91

Answers (2)

camickr
camickr

Reputation: 324207

You should be able to use a JLayer to paint different images (icons) on top of the label.

Read the section from the Swing tutorial on How to Decorate Components With the JLayer Class. The section on Animating a Busy Indicator would seem similar to what you want to do.

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285450

Yes, you are starting your Thread correctly, but you're making Swing state-changing calls, setIcon(...) from within your background thread, and that is risky.

Myself, I'd use a Swing Timer to drive my animation as with a timer, all calls in its ActionListener will be made on the Swing event thread, making for a safer loop. I'm not sure that I'd extend JLabel for this, since I'm not changing any of the class's innate behavior. Rather I'd use a JLabel.

I'd also add a MouseListener to my label and on mousePressed, I'd stop this Timer and start the explosion animation Timer.

Upvotes: 2

Related Questions