0

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

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
ats27
  • 3
  • 2

1 Answers1

2

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.

Community
  • 1
  • 1
camickr
  • 321,443
  • 19
  • 166
  • 288
  • thanks that worked, but how about if I want to take the input from the main JFrame I am working on? can I delay the return method then? – ats27 Jan 03 '14 at 19:12
  • @ats27, what do you mean "take the input from the main frame"? How do you know the user is finished typing the input. The user will click a button or something like that to indicate they are finished. Then you get the input. – camickr Jan 03 '14 at 20:46
  • That wasn't clear on my part, sorry. I mean taking an input in the latter question such as clicking on an image on the main frame for example if I have bunch of images or buttons on the main frame and every one of them should returns a different value – ats27 Jan 03 '14 at 20:56