Java JToggleButton在While循环中冻结
这是我的一段代码,基本上当按下一个按钮时,它每分钟播放X次点击 我尝试过这样的while循环代码:Java JToggleButton在While循环中冻结,java,swing,if-statement,while-loop,jtogglebutton,Java,Swing,If Statement,While Loop,Jtogglebutton,这是我的一段代码,基本上当按下一个按钮时,它每分钟播放X次点击 我尝试过这样的while循环代码: public void playMet() { int tempo = Integer.parseInt(met_speed.getText()); tempo = tempo/60; int delay = tempo*1000; if(Play.isSelected()) { try { FileInputStrea
public void playMet() {
int tempo = Integer.parseInt(met_speed.getText());
tempo = tempo/60;
int delay = tempo*1000;
if(Play.isSelected()) {
try {
FileInputStream in = new FileInputStream(new File("Click1.wav"));
AudioStream as = new AudioStream(in);
AudioPlayer.player.start(as);
Thread.sleep(tempo*1000);
playMet();
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
else
System.out.println("not playing");
}
这也没用。在这两种情况下,程序运行正常,但冻结,我必须从任务管理器关闭它
当按下按钮时,如何调用函数,如果取消选择,如何停止该函数
p.S.刚刚看到下面的两个帖子。我必须去上班,我会稍后检查他们,看看他们是否工作。谢谢您的帮助。递归调用正在阻止。您必须创建一个新线程,以不阻止EDT
while(Play.isSelected()) {
.........
.........
}
您不需要Thread.sleep(),也不需要递归或while循环。 你需要有状态的玩家。你的用户界面应该只改变播放器的状态 请参见中的示例
private final ScheduledExecutorService executor=Executors.newSingleThreadScheduledExecutor();
私有调度的未来播放任务;
私有文件输入流播放;
公共空间playMet(){
停止铺设();
playingTask=executor.scheduleWithFixedDelay(new Runnable()){
@凌驾
公开募捐{
playMet();
}
},0,1000,时间单位为毫秒);
}
公共空间游乐场(){
试一试{
IOUtils.close(播放);
播放=新文件输入流(新文件(“Click1.wav”);
AudioStream as=新的AudioStream(播放);
AudioPlayer.player.start(as);
}捕获(例外e)
{
showMessageDialog(null,e);
}
}
公众假期{
试一试{
AudioPlayer.player.stop();
IOUtils.close(播放);
播放=空;
if(playingTask!=null){
playingTask.cancel(false);
}
playingTask=null;
}捕获(例外e){
showMessageDialog(null,e);
}
}
他想反复播放声音,直到用户停止播放
public void playMet()
{
Thread t = new Thread(new Runnable()
{
@Override
public void run()
{
while(Play.isSelected()){
//Your code
}
}
};
t.start();
}
private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
private ScheduledFuture<?> playingTask;
private FileInputStream playing;
public void playMet() {
stopPlaying();
playingTask = executor.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
playMet();
}
}, 0, 1000, TimeUnit.MILLISECONDS);
}
public void playMetOnce(){
try {
IOUtils.close(playing);
playing = new FileInputStream(new File("Click1.wav"));
AudioStream as = new AudioStream(playing);
AudioPlayer.player.start(as);
} catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
public void stopPlaying(){
try {
AudioPlayer.player.stop();
IOUtils.close(playing);
playing = null;
if (playingTask != null) {
playingTask.cancel(false);
}
playingTask = null;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}