Hi!
I have a recursive method that changes the value of a variable in every recursion, then it shows that value on the JPanel, and then I would like to pause (here is my problem) until I click (it pauses in every new recurse). Then when I click this method continues to do the next recursion.
The following code is just the structure of how my real program looks like and how I tried to implement that. I have tried many ways to do that thing using threads and executors but I failed.
I have created 2 classes, the PanelToBeClicked
class which is a JPanel and has the recursive method, and a PanelMouseListener
class which collects the clicks.
The following code is totally naked from threads and executors. I would be very grateful if someone could add some lines of code here to demonstrate the correct approach, or give me some clues of how I can implement it.
Here is the code:
import java.awt.*;
import javax.swing.*;
public class PanelToBeClicked extends JPanel {
int counter;
public PanelToBeClicked() {
super();
setPreferredSize(new Dimension(100,100));
addMouseListener(new PanelMouseListener(this));
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString("" + counter, 10, 10);
}
public void recursiveMethod(){
counter++;
repaint();
/*
* Pause/wait until the panel is clicked so you proceed the recursions
* MISSING CODE HERE. I tried thread.sleep
* but I had a monitor exception
*/
if (counter <10)recursiveMethod();
}
public static void main(String[] args) {
final JFrame frame = new JFrame("How can i do that?");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new PanelToBeClicked());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
frame.pack();
frame.setVisible(true);
}
});
}
}
The listener:
public class PanelMouseListener extends MouseAdapter {
private PanelToBeClicked panelToBeClicked;
public PanelMouseListener(PanelToBeClicked panelToBeClicked) {
this.panelToBeClicked = panelToBeClicked;
}
@Override
public void mouseClicked(MouseEvent e) {
/*
* start the method PanelToBeClicked.recursiveMethod()...
*/
panelToBeClicked.recursiveMethod();
/*
* if the method is already running and it is not paused do nothing.
* ** MISSING CODE
* if the method is running and is paused then make the method to continue the recursions
* **MISSING CODE */
}
}