如何在 Java GUI 中为单选按钮添加声音效果?例如,单击单选按钮时会发出咔嗒声。请告诉我并解释一下方法。
几年前我没有尝试或复制 YouTube 上的所有这些示例和解释,因为它们有点模糊而且并不夸张,我只是真的想知道如何做到。我只是想知道什么是基础知识请分享。谢谢你。
我已经有一段时间没有这样做了。 我想说的是,在你的动作处理程序中,你想要获取声音然后播放它。 所以像这样:
JButton b1 = new JButton("Cool button"); // Make button
// Create action listener - play the sound when the button is pressed
ActionListener listener = new ActionListener() {
File localSoundFile = new File("path_to_sound");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(localSoundFile);
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
// Other action handler stuff
}
b1.addActionListener(listener); // Attatch listener to the button
更改代码以适用于您正在使用的任何 GUI 框架,但整体设计应该类似