【发布时间】:2009-07-26 10:55:58
【问题描述】:
我有一个递归方法,可以在每次递归中更改变量的值,然后在 JPanel 上显示该值,然后我想暂停 (这是我的问题),直到我单击(它会在每个新的递归中暂停)。然后当我点击这个方法时继续做下一次递归。
以下代码只是我的真实程序的结构以及我如何尝试实现它。我已经尝试了很多方法来使用线程和执行器来做这件事,但我失败了。
我创建了 2 个类,PanelToBeClicked 类是一个 JPanel 并具有递归方法,以及一个 PanelMouseListener 类收集点击。
以下代码完全没有线程和执行程序。如果有人可以在这里添加一些代码行来演示正确的方法,我将不胜感激,或者 给我一些关于如何实现它的线索。
代码如下:
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);
}
});
}
}
听者:
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 */
}
}
【问题讨论】:
标签: java multithreading