我想问一下,在一个JButton上操作,当鼠标经过一个JButton上时会发一个声音的效果(如:一水滴声),这个效果怎么搞去来,希望高人指点一下,谢谢。。给出相应的代码。

解决方案 »

  1.   

    package com.org.timer;import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;import javax.swing.JButton;
    import javax.swing.JFrame;import sun.audio.AudioPlayer;
    import sun.audio.AudioStream;public class ButtonSound extends JFrame implements MouseListener {
    //加入 serialVersionUID 防止警告错误 没什么特殊意义
    private static final long serialVersionUID = 1L;
    private JButton mybuttion;
    private Container content; public ButtonSound() {
    // 设置版面位置 1024*768 居中
    this.setLayout(new FlowLayout());
    this.setBounds(412, 294, 200, 120);
    this.setResizable(false); content = this.getContentPane();
    content.setLayout(null); mybuttion = new JButton("音乐按钮");
    mybuttion.setBounds(50, 30, 100, 30);
    mybuttion.addMouseListener(this);
    this.add(mybuttion); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true); }
    //播放声音的方法
    public void palySound() {
    AudioStream as = null;
    FileInputStream inStreamObj = null;
    try {
    //C:/WINDOWS/Media/Windows XP 启动.wav 
                            //这个路径是 windows XP 默认的开机音乐的路径
    //有需要 可以自己改 但是JAVA支持的音乐文件只有 .wav .au .MIDI
                            //等格式 不要拿MP3等文件
    inStreamObj = new FileInputStream("C:/WINDOWS/Media/Windows XP 启动.wav");
    as = new AudioStream(inStreamObj);
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }
    AudioPlayer.player.start(as);
    } public void mouseClicked(MouseEvent e) {
    // 鼠标单击事件 } public void mouseEntered(MouseEvent e) {
    // 移动到 也就是我们需要的
    palySound(); } public void mouseExited(MouseEvent e) {
    // 移动开 } public void mousePressed(MouseEvent e) {
    // 按下 } public void mouseReleased(MouseEvent e) {
    // 释放 } public static void main(String[] args) {
    new ButtonSound();
    }}
    -------------------------------------------
    很完美 给分吧
      

  2.   

    好像sum发布了个支持mp3格式的包的!
      

  3.   

    我想因该要,WAV都可以放了,MP3的也可以的,同一个性质的,只是没有找到。。