Karczu
Karczu

Reputation: 1

java: how to delay code in GUI

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

Upvotes: 0

Views: 765

Answers (1)

Durandal
Durandal

Reputation: 20069

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.

Upvotes: 3

Related Questions