Search code examples
javaswingtimerawtdelay

How to delay a return statement in java using Timers


I have a method that returns a certain int variable, but this variable should be modified by the user using a JFrame that pops out when this method is called before it's returned. So I thought of using a timer that would delay the return statement by certain a more-than-needed number of seconds and when the button for example is pressed, the timer would stop and the variable would change

Here is the method:

public static int c(){

    x.setVisible(true);// x is the name of the frame
    timer.schedule(new TimerTask() {
        public void run() {
            System.out.println("Text");
        }
    }, 5000);
    return q;
}

And here is the ActionListener set on the button in the constructor:

    d.addActionListener(new ActionListener(){ //d is the name of the button
        @Override
        public void actionPerformed(ActionEvent arg0) {
            q=5;
            timer.cancel();
            x.setVisible(false);
        }
    }); 

But all it does is delaying the printing statement inside the run method, and of course i cannot return inside the delayed task since its type is void

Thanks


Solution

  • but this variable should be modified by the user using a JFrame that pops out when this method is called before it's returned

    An application should only have a single main JFrame (see: The Use of Multiple JFrames: Good or Bad Practice?). Child windows should be a model JDialog. Then when show the dialog, the code after the setVisible() statement will not execute until the dialog is close.

    You can create you own custom JDialog or it may be easier to use a JOptionPane. See the section from the Swing tutorial on How to Make Dialogs for more information and examples.