我试图把游戏方法在我的Audioapp
类在我的ActionListener
,我试着把它,但得到错误。
我已经阅读了关于ActionListener
的javadoc,但找不到它
这是我的音频:
public class Audioapp extends JApplet // find out how to implement play method into action listener?
{
public class Sound // Holds one audio file
{
private AudioClip song; // Sound player
private URL songPath; // Sound path
Sound(String filename)
{
try
{
songPath = new URL(getCodeBase(),"G:\Uni\Programming\Rolling assignements\Week0\Programming week21"); // This is the place were im getting error
song = Applet.newAudioClip(songPath); // Load the Sound
}
catch(Exception e){e.printStackTrace();}
}
public void playSound()
{
song.play(); // Play
}
}
}
这是我的actionListener
:
class PlayStoHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String computerRand = sps.computerChoice();
txtComputerRand.setText(computerRand);
String result = sps.play(Sps.ROCK);
txtResult.setText(result);
scis.setVisible(false);
open.setVisible(false);
stone.setVisible(true);
pap.setVisible(false);
win.setVisible(false);
none.setVisible(false);
lose.setVisible(false);
if (result == "User Wins"){
win.setVisible(true);
song.play(); // here i tried putting the song.play in this if section, the error I got was "song cannot be resolved"
}
else if (result == "Draw"){
none.setVisible(true);
}
else {
lose.setVisible(true);
}
}
我是初学者,所以这很可能是一个非常愚蠢的基本错误
如有任何帮助,不胜感激
songPath = new URL(getCodeBase(),"G:\Uni\Programming\Rolling assignements\Week0\Programming week21");
URL构造函数期望第二个字符串表示一个相对URL,而您已经放置了一个文件路径。URL总是有正斜杠,基于file:
的URL没有什么意义(WAV托管在您的网站上,而不是最终用户的高清)。
如果applet是通过HTML在站点的根目录加载的,而HTML中没有声明codebase
,并且wav名为moo.wav
并且位于名为Week0/Programming week21
的子目录中,那么正确的路径将是:
songPath = new URL(getCodeBase(),"Week0/Programming week21/moo.wav");
但是为了使事情简单得多,至少现在,把HTML、applet 和剪辑放到相同的目录并使用:
songPath = new URL(getCodeBase(),"moo.wav");
song
是private。您创建了一个方法来播放声音,所以请使用它。
获取Audioapp
的实例并运行playSound()
方法