【发布时间】:2022-01-09 02:40:31
【问题描述】:
我正在为音乐播放器制作 GUI 我有 2 个按钮,我想在同一个线程上运行,但在不同的动作听众上,一个是播放音乐,一个是停止音乐。这是我的代码:
ActionListener bl2 = new ActionListener() { // play button
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("listener1" + Thread.currentThread().getName());
System.out.println("beep"); //created a new thread here so that my GUI won't freeze up
Runnable runnable = () -> {
cl.play();
};
Thread thread = new Thread(runnable);
thread.start();
}
};
ActionListener bl3 = new ActionListener() { //supposedly to stop the music which the other thread is running
@Override
public void actionPerformed(ActionEvent e) {
cl.stop();
}
};
我还有一个暂停按钮可以暂停音乐。我的问题是,当我单击它执行的 GUI 中的停止按钮时,我不知道如何停止我的音乐(我在调用它时打印出该方法)但不会停止音乐,这就是为什么我认为停止我的音乐我需要在播放按钮运行的同一线程中调用我的方法,这是正确的吗?我怎么做?谢谢。
【问题讨论】:
标签: java multithreading user-interface awt actionlistener