[英]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. 我只想确保下次单击该特定按钮时,notin会发生。
You can put a global boolean variable and initially set it to false. 您可以放置一个全局布尔变量,并将其初始设置为false。 When the mouse button is clicked, check first if the variable is false before continuing to play the audio.
单击鼠标按钮后,请先检查变量是否为false,然后再继续播放音频。 Do not proceed if the variable is true.
如果变量为true,则不要继续。 If the variable is false, you can set it to true and then continue the code to start playing the audio.
如果变量为false,则可以将其设置为true,然后继续执行代码以开始播放音频。
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. 也许程序的某些部分具有检测音频是否已完成播放的代码,您可以在此处将变量设置为false,以便单击按钮时可以再次播放音频。
For a button that you only want to act once, you can use setEnabled(false) after one action: 对于只想操作一次的按钮,可以在一个操作之后使用setEnabled(false):
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. 对于JLabel,我必须使用MouseListener而不是ActionListener。 The MouseAdapter is a MouseListener with methods I don't care about stubbed out.
MouseAdapter是一个MouseListener,具有我不在乎的方法。 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;
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.