1

I am developing a program by using JFrame and i want to realize that when you click on a button, a loop in a other class has to work. It is working but so slowly. In one second you can see just one iteration of the loop. I dont understand why. There are pieces of codes you need to know. Calling listener:

playWithComputerButton.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            startLoop(1);
        }
    });

called piece:

if(gameMode == 2){
        int i = 0;
        while(i < 500){
            int pos = ((Computer) playerA).thinkIt(board.getBoard());
            display("bu pas : " + pos);
            i++;
        }

There is no problem with iteration and calling listener. (i have tried it also with other iterations and 'ActionListener' but the result is same.

What can be the solution?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
AsqaN
  • 11
  • 3
  • 4
    You need to use `SwingWorker` to perform long operations not related to GUI – Nikolay Kuznetsov Dec 14 '12 at 05:11
  • 1
    I'd suggest having a quick read this [answer](http://stackoverflow.com/questions/13870982/updating-swing-components-correctly/13871140#13871140), while it's not a direct answer, it will highlight the problems you are having and why Nikolay's answer is actual correct – MadProgrammer Dec 14 '12 at 05:33
  • 1
    _There are pieces of codes you need to know._ Rather than pieces, please edit your question to include an [sscce](http://sscce.org/) that focuses on the problem. Several examples are cited [here](http://stackoverflow.com/a/8237370/230513). – trashgod Dec 14 '12 at 10:35
  • it was preciesly what i was looking for. It is now working without any slowness! Thank you Nikolay and Madprogrammer. @trashgod, thank you for your feedback. i'll do it. – AsqaN Dec 14 '12 at 14:49

1 Answers1

0

To perform long operations not related to GUI, we can simply make use of javax.swing.SwingWorker, as Nikolay Kuznetsov and MadProgrammer explained above.

Here is a example of how to use it: example and here is the javadoc of SwingWorker: javadoc

in case of my program, the solution is:

Firstly create a new SwingWorker extending class in your JFrame class

class LoopWorker extends SwingWorker<Integer, Integer>
{
    protected Integer doInBackground() throws Exception
    {
        // perform your loop
    }

    protected void done()
    {
        // what has to be done after performing
    }
}

Then, the button should call its execute method as follow:

learnButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            new LoopWorker().execute();
        }
     });
Community
  • 1
  • 1
AsqaN
  • 11
  • 3