0

I am making a programme in Java for a school project. It has the form of an interactive multiple-choice test.

I wanted it to perform it in a way that an action button creates an event in which (the order of the code is the same as listed):

1) Randomly chooses an Object that consist of several Strings from a prepared List and prints it on adequate text fields in GUI

2) Using a proper method there is a delay created that holds further code down below for 1 minute. In this time the user should be able to check proper Checkboxes so the GUI must stay active.

3)When this minute ends the checked places are read and further processed.

The thing is that I am unable to create step number 2) which is the delaying of the code below. I have tried function sleep() but when I do it with sleep() the whole GUI freezes and the user is unable to do anything on it. I have read that function swing timer would be appropriate but I dont know how to do it. I have seen examples but in them the timer along with functions that were executed after some time were written in the class ActionListener instead of the action button. I am using Netbeans 8.1

Sorry for my bad explanation of the problem, I am a total beginner in java programming and really count on your help :) Cheers!

enter image description here

David Yee
  • 3,515
  • 25
  • 45
Karczu
  • 1
  • 1
  • Possible duplicate of [How could I add a simple delay in a Java Swing application?](http://stackoverflow.com/questions/12767367/how-could-i-add-a-simple-delay-in-a-java-swing-application) – BillRobertson42 Feb 05 '16 at 21:15

1 Answers1

3

Your problem comes from how you structured your code. You wrote everything into a single method.

Split this up into two methods. One to set up the UI state (everything before "HERE I NEED TO DELAY..."). The second method takes everything below.

Then, at the end of the first method, create a non-repeating Timer for one Minute, add an ActionListener that just calls your second method. Then start the timer. When the timer has run its course, it will call your second method through the action listener.

Durandal
  • 19,919
  • 4
  • 36
  • 70
  • Ok, I think I have the working timer but in the picture of the code I provided, you can see that I want everything done three times. Right now it behaves as if this loop did not exist and I really can't tell why :/ The loop's curly braces start at the beginning and end at the very end of the JButton method. – Karczu Feb 06 '16 at 14:46