如何创建一个按两次按钮时暂停的jToggle按钮?

时间:2017-03-16 19:53:17

标签: java netbeans toggle

我一直绞尽脑汁想要让这个循环的wav在第二次点击时暂停, 我哪里错了?

private void jToggleButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                               
        JToggleButton btn = (JToggleButton) evt.getSource(); 
            if (btn.isSelected()) { 
            try { 
                String soundName = "yourSound.wav";
                AudioInputStream audioInputStream = null;
                try {
                    audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile());
                } catch (UnsupportedAudioFileException | IOException ex) {
                    Logger.getLogger(GEN.class.getName()).log(Level.SEVERE, null, ex);
                }
                Clip clip = null;
                try {
                    clip = AudioSystem.getClip();
                } catch (LineUnavailableException ex) {
                    Logger.getLogger(GEN.class.getName()).log(Level.SEVERE, null, ex);
                }
                clip.open(audioInputStream);
                clip.start();
                clip.loop(100);
            } catch (LineUnavailableException | IOException ex) {
                Logger.getLogger(GEN.class.getName()).log(Level.SEVERE, null, ex);
            }
            } else { 
            try {
} 

1 个答案:

答案 0 :(得分:0)

帮助OP的解决方案概要:

private Clip clip; // declared outside the method

private void jToggleButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    JToggleButton btn = (JToggleButton) evt.getSource();
    if (btn.isSelected()) {
        // initialize `clip` variable, if not done already
        // call start() if not running
    } else {
        if (clip != null && clip.isRunning()) {
            clip.stop();
        }
    }
}