-1

I´ve been trying to make a multiple choice question game using swing elements, I am just using a JTextArea to show the questions and four JButtons for the options.

I would like that every time the user answer a question the correct answer is shown by changing the background color of the JButton with the correct answer.

I am using a MVC design pattern so each time the user clicks the options JButtons the actionPerformed method calls a method in the interface that sets the background color of the JButton, sleeps the thread for one second and then it sets the background to the default color.

Everything seems to be right however when a run the program the graphic interface doesn't change the background color, although you can see the thread sleep.

If someone could help me solve this problem i would be very grateful, I include the code of all the described methods.

public void showCorrectAnswer (int index)
{
    //JButtons array
    options[index].setBackground(Color.green);
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    options[index].setBackground(defaultColor);
}

ActionPerformed code of option buttons:

public void actionPerformed(ActionEvent e)
{
    JButton source = (JButton) e.getSource();
    int index =controller.getTheModel().getIndexWereTheRightAnswerIs();
    controller.getTheMainView().showCorrectAnswer(index);

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366

1 Answers1

0

Using Thread.sleep from within the context of the Event Dispatching Thread is preventing the EDT from processing new paint requests (the changing of the background color).

Swing is also not thread safe, this means that you should only modify the UI from the context of the EDT.

Instead, you should consider using a javax.swing.Timer instead. This will allow you to schedule a callback at some time in the future and, when triggered, take action that will be executed from within the context of the EDT.

Take a look at Concurrency in Swing and How to Use Swing Timers for more details

What I would do is set up a non-repeating timer with a one second delay, set the background color of the button and start the timer. When the timer triggers, reset the background color of the button

Also, depending on the look and feel, setting the background color of the button may not have any (or only a small) effect, just so you know...

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366