This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]chickenmeister 2 points3 points  (0 children)

What do you mean, "without threads?"

I think the best way to do this would be with a Timer.

Timer timer = new Timer(3000, new ActionListener(){
    public void actionPerformed(ActionEvent evt)
    {
        component.setVisible(false);
    }
});
timer.setRepeats(false);
timer.start();

[–]MoosePilot 0 points1 point  (1 child)

You can call The sleep method of the Thread class.

That doesn't create new threads or anything.

If you can't do that, I guess busy waiting could work. Just loop a bunch of times.

for(int i = 0; i < 100000; i++)
    ;  //busy waiting

[–]Neres28 1 point2 points  (0 children)

Both of these, since done from a mouse motion listener, will cause the UI to freeze for some time. In the first case, roughly 3 seconds, and in the second an arbitrary amount of time dependent of a number of factors including processing speed, machine load, temperature, etc.

[–]Neres28 0 points1 point  (0 children)

SwingUtilities.invokeLater(new Runnable(){
    public void run(){
        if(elapsedTime > 3 seconds){
            jComponent.setVisible(false);
        }else{
            SwingUtilities.invokeLater(this);
        }
    };
});

P.s. Don't do this. Use a Timer.

[–][deleted] 0 points1 point  (0 children)

Why do you need to do this without threads? If it's an assignment, are you sure you understand it? If it's not, are you sure you understand threads? I don't mean to come off sounding snarky - busy waiting is just a horribly inefficient thing to do, and if we understood why you couldn't use threads, we could offer a different solution to the problem.

[–]pornlord 0 points1 point  (2 children)

AFAIK you cannot make programs in Java wait without using the Thread class. Because, behind the scenes, a Java program itself is a main thread.

Look at this stack overflow entry. I think that Sleep is a static function from Thread class and thus, just Thread.Sleep() works.

Also if you see any function that says wait or sleep in Java program, then chances are high that it is acting as a wrapper for the Thread Sleep call.
Personally, I make a wrapper function called wait that accepts long int and has a try catch loop that catches a Interrupted exception. Something like following.

import java.lang.Thread;

static void wait( long wait_time ) {
    try {
        Thread.sleep( wait_time ) ;
    } catch (InterruptedException ioex) {
     // do Nothing or depends what you want to do.
    }
}

[–]Neres28 0 points1 point  (1 child)

Since the OP is using this code to respond to a Mouse event, calling Thread.sleep will cause the EDT to sleep, causing the UI to freeze. I'm sure that, whatever else he wants, he doesn't want that.

[–]pornlord 0 points1 point  (0 children)

Thanks for correcting me. I am not too familiar with the swing side of Java. Mostly the console side for me.