在addActionListener,JAVA中找不到fileName

时间:2015-07-31 19:03:12

标签: java function button jframe actionlistener

我试图在用户点击按钮时创建播放音频的功能。问题是,当我尝试使用" fileName.addActionListener"从参数传入fileName时,它表示即使在参数中引用了fileName,也无法找到它。我做错了什么,我该如何解决这个问题?感谢。

package sunaudiodemo;

import static java.awt.Color.blue;
import static java.awt.Color.green;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import sun.audio.*;    //import the sun.audio package
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

public class SunAudioDemo {


    public static void playAudioOnClick (final String fileName) {

        //******************************************* 
    fileName.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
        try {
            playAudio(fileName);
        } catch (Exception ex) {
            Logger.getLogger(SunAudioDemo.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    });
    //*******************************************

    }

    public static void playAudio (String text) throws Exception {

        // identify the sound file as a File class object
        File soundFile = new File(text);

        // Open an input stream for the File object soundFile
        // This allows Java to read the file.
        InputStream inFile = new FileInputStream(soundFile);

        // Create an AudioStream from the input stream.
        // This tells Java to read the incoming data as sound data.
        AudioStream audio = new AudioStream(inFile);

        // play the sound file using the start method from Audioplayer.player
        AudioPlayer.player.start(audio);

    }

    public static void main(String[] args) throws Exception {


 // create a frame to hold our components
 JFrame myJFrame = new JFrame();
 // create a new a grid layout for the frame - 5 rows x 2 cols, gaps=20
 GridLayout myLayout = new GridLayout(5,2);
 myLayout.setHgap(20);
 myLayout.setVgap(20);

 // assign myLayout to be the layout for MyJFrame
 myJFrame.setLayout(myLayout);

 // Create a button with text OK
 JButton wav1 = new JButton("Play Audio 1");
 myJFrame.add(wav1); // Add the OK button
 playAudioOnClick("wav2.wav");


 // set the title, size, location and exit behavior for the JFrame
 myJFrame.setTitle("Play Audio");
 myJFrame.setSize(360, 480);
 myJFrame.setLocation(200, 100);
 myJFrame.getContentPane().setBackground( green );
 myJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 // make the frame visible (activate the frame)
 myJFrame.setVisible(true); 



    } // end main()

} // end class SunAudioDemo

1 个答案:

答案 0 :(得分:1)

在上面的代码中,fileName被定义为String。假设这是java.lang.String,则没有方法addActionListener()。您需要传入对按钮的引用,以便可以向其添加ActionListener。