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?
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
Then, the button should call its execute method as follow: