简体   繁体   中英

how to make button perform action once

I want a button to make a sound, but after just one click. But keeps playing again and again when clicked. How do I make the sound play ones , then play again on the next page.

Here is the code

Private void buttonMouseClicked
Audioinput audio =AudioStream.getAudioInputStream(this.get class().getResource ("/AppPackage/BH/chr.wav"));
Clip clip =AudioSystem.getClip();
clip.open(audio);
clip.start();

I just want to make sure notin happens when next this particular button is clicked.

You can put a global boolean variable and initially set it to false. When the mouse button is clicked, check first if the variable is false before continuing to play the audio. Do not proceed if the variable is true. If the variable is false, you can set it to true and then continue the code to start playing the audio.

boolean isPlaying = false;

private void buttonMouseClicked() {
    if (isPlaying) return;
    isPlaying = true;

    AudioInputStream audio;
    try {
        audio = AudioSystem.getAudioInputStream(getClass().getResource("/AppPackage/BH/chr.wav"));
        Clip clip;
        clip = AudioSystem.getClip();
        clip.open(audio);
        clip.start();
    } catch (UnsupportedAudioFileException ex) {
        ex.printStackTrace();
    } catch (LineUnavailableException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }        
}

Maybe some part of your program has a code to detect if the audio has finished playing, you can set the variable back to false there so that you can play the audio again when you click the button.

For a button that you only want to act once, you can use setEnabled(false) after one action:

JButton myButton = new JButton("Only works once");
myButton.addActionListener(e -> {
    // Code for thing i only do once.
    // ...
    myButton.setEnabled(false);
});

For a JLabel I have to use a MouseListener instead of an ActionListener. The MouseAdapter is a MouseListener with methods I don't care about stubbed out. This means disabling it won't help and I need to add an extra variable to save the fact that it is already clicked.

JLabel myLabel = new JLabel("label you can click on once");
myLabel.addMouseListener(new MouseAdapter() {

        boolean alreadyclicked = false;
        @Override
        public void mouseClicked(MouseEvent e) {
            if(!alreadyclicked) {
                // Code for doing stuff I only want to do once.
                alreadyclicked = true;
            }
        }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM