我不知道怎么做但是我希望我的JButton在按下时开始运行一个方法,然后当我再次点击它时暂停该方法。此外,该方法应该连续运行。 现在,我的按钮不会暂停和启动,也不会连续运行。
private JButton playButton = new JButton("Play!");
playButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
?????
}
我知道我的问题的答案就在那里,但我的尝试刚刚在一个牢不可破的while循环中结束。
我问别人,我被告知我必须在一个单独的线程中运行一些东西。问题是,我对线程一无所知。没有线程,有没有其他方法可以做到这一点?
答案 0 :(得分:0)
实现一个连续运行的函数/方法,直到被外部信号告知停止......没有线程很难做到。 GUI元素的事件处理程序本质上与应用程序逻辑在不同的线程上运行,因为如果两者同步运行(即按钮控件等待一些处理在能够再次接受点击事件之前完成)...这样申请会很糟糕。这是真事,哥们。
答案 1 :(得分:0)
boolean running = false;
private JButton playButton = new JButton("Play!");
Thread stuff = new Thread(new RunningThread());
playButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
if (!running) {
stuff.start();
running = true;
}
else {
if (stuff.isAlive()) {
stuff.stop();
}
running = false;
}
}
public class RunningThread implements Runnable {
public RunningThread() {
}
@Override
public void run() {
//DO STUFF: You also want a way to tell that you are finished and that the next button press should start it up again, so at the end make a function like imDone() that sends a message to your page that changes running = false;
}
}
这样的事情应该有效。唯一的问题是这是停止而不是停顿。暂停会有点棘手,取决于函数内部究竟发生了什么。