鼠标点击按钮时添加按键声音
如题...请问怎么做?
------解决方案--------------------
==播放背景音乐,你添加到监听器里就可以了
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import
java.io.IOException;
import java.io.InputStream;
import javax.sound.midi.InvalidMidi
DataException;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Midi
UnavailableException;
import javax.sound.midi.Sequencer;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
public class MusicBox extends JFrame {
private Sequencer sequencer;
private String songPath;
private byte[] data;
public static void main(String[] args)
{
JFrame frm = new MusicBox("Dummy Midi Player.", "25min.mid");
frm.setDefaultCloseOperation(EXIT_ON_CLOSE);
frm.pack();
frm.setVisible(true);
}
public MusicBox(String title, String songPath)
{
super(title);
this.songPath = songPath;
InputStream resIn = getClass().getResourceAsStream(songPath);
try {
ByteArrayOutputStream out = new ByteArrayOutputStream(resIn.available());
byte[] buf = new byte[10000];
int bytes;
while ((bytes = resIn.read(buf)) != -1)
out.write(buf, 0, bytes);
resIn.close();
out.close();
data = out.toByteArray();
}
catch (
IOException e2) {
e2.printStackTrace();
}
try {
sequencer = MidiSystem.getSequencer();
sequencer.open();
addWindowListener(new WindowAdapter() {
public void windowOpened(WindowEvent e)
{
try {
sequencer.setSequence(new ByteArrayInputStream(data));
sequencer.start();
}
catch (IOException e1) {
e1.printStackTrace();
}
catch (InvalidMidiDataException e1) {
e1.printStackTrace();
}
}
public void windowClosed(WindowEvent e)
{
sequencer.stop();
sequencer.close();
}
});
}
catch (MidiUnavailableException e) {
e.printStackTrace();
}
initComponents();
}
private void initComponents()
{
JLabel label = new JLabel("Now playing: " + songPath);
label.setFont(Font.decode("Dialog-PLAIN-24"));
label.setForeground(new Color(0x7B68EE));
getContentPane().add(new JScrollPane(label));
JButton button = new JButton("Click me");
Box box = Box.createHorizontalBox();
getContentPane().add(box, BorderLayout.SOUTH);
box.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
box.add(Box.createHorizontalGlue());
box.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(getContentPane(), "You got it!");
}
});
}
}