java编写程序实现键盘钢琴,运用键盘事件、鼠标事件
界面 实现 MouseListener,MouseMotionListener,KeyListener接口,当鼠标进入不同按钮时,会播放不同的声音。当点击键盘上的1~0时,会播放不同的声音。
Win.java
package piano;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.FileInputStream;
import sun.audio.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;
public class win extends JFrame implements MouseListener,MouseMotionListener,KeyListener{
JPanel p=new JPanel();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
JButton b0=new JButton("0");
JLabel a=new JLabel("Melodies and numbers");
JLabel b=new JLabel("Press on your key numbers and play melody.");
win(){
init();
setVisible(true);
setBounds(300,200,650,360);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init(){
p.setLayout(null);
setTitle("键盘钢琴");
p.setBackground(Color.pink);
a.setFont(new Font("Axure Handwriting",Font.BOLD,50));
a.setForeground(Color.red);
b.setFont(new Font("Axure Handwriting",Font.BOLD,20));
b.setForeground(Color.black);
a.setBounds(50,50,600,100);
b.setBounds(50,230,600,100);
b1.setBounds(50,150,50,90);
b2.setBounds(105,150,50,90);
b3.setBoun