static代表“每个类一个”而不是“每个对象一个”。即静态变量是类的所有对象共有的。
1 static JFrame f; 2 static MyDrawPanel ml;
整个应用程序如下:
定义在public void go(){...}里面的变量的生存空间仅仅是这个方法,出了这个方法,其他的类和方法是没法调用这个·方法里定义的变量的。
1 import javax.sound.midi.ControllerEventListener; 2 3 import javax.sound.midi.MidiEvent; 4 import javax.sound.midi.MidiSystem; 5 import javax.sound.midi.Sequence; 6 import javax.sound.midi.Sequencer; 7 import javax.sound.midi.ShortMessage; 8 import javax.sound.midi.Track; 9 import javax.swing.JFrame; 10 import javax.swing.*; 11 import java.awt.*; 12 13 import java.io.*; 14 15 public class MiniMusicPlayer3 { 16 //JFrame frame; 17 static JFrame f=new JFrame("My first music Video"); 18 static MyDrawPanel ml; 19 public static void main(String[] args){ 20 MiniMusicPlayer3 mini=new MiniMusicPlayer3(); 21 mini.go(); 22 } 23 public void go(){ 24 //frame=new JFrame("My first music Video"); 25 //MyDrawPanel myDraw=new MyDrawPanel(); 26 ml=new MyDrawPanel(); 27 //f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 28 f.getContentPane().add(ml); 29 //f.getContentPane(ml); 30 f.setBounds(30,30,400,400); 31 f.setVisible(true); 32 try{ 33 Sequencer player=MidiSystem.getSequencer(); 34 player.open(); 35 36 int[] eventsIWant={127}; 37 player.addControllerEventListener(ml,eventsIWant); 38 39 Sequence sequence=new Sequence(Sequence.PPQ,4);//什么意思,待会查一查。 40 Track track=sequence.createTrack(); 41 int r=0; 42 for(int i=5;i<60;i+=4){ 43 r=(int) ((Math.random()*50)+1); 44 track.add(makeEvent(144,1,r,100,i)); 45 46 track.add(makeEvent(176,1,127,0,i)); 47 48 track.add(makeEvent(128,1,r,100,i+2)); 49 50 } 51 52 player.setSequence(sequence); 53 player.setTempoInBPM(120); 54 player.start(); 55 }catch(Exception ex){ex.printStackTrace();} 56 57 58 59 } 60 61 public MidiEvent makeEvent (int comd,int chan,int one,int two,int tick){ 62 MidiEvent event=null; 63 try{ 64 ShortMessage a=new ShortMessage(); 65 a.setMessage(comd,chan,one,two); 66 event=new MidiEvent(a,tick); 67 }catch(Exception e) {} 68 return event; 69 } 70 71 72 class MyDrawPanel extends JPanel implements ControllerEventListener{ 73 boolean msg=false; 74 75 public void controlChange(ShortMessage event){ 76 msg=true; 77 repaint(); 78 79 } 80 81 public void paintComponent(Graphics g){ 82 if(msg){ 83 Graphics2D g2d=(Graphics2D) g; 84 int red=(int) (Math.random()*255); 85 int green=(int) (Math.random()*255); 86 int blue=(int) (Math.random()*255); 87 Color randomColor=new Color(red,green,blue); 88 g2d.setColor(randomColor); 89 90 int ht=(int) ((Math.random()*120)+10); 91 int width=(int) ((Math.random()*120)+10); 92 93 int x=(int) ((Math.random()*40)+10); 94 int y=(int) ((Math.random()*40)+10); 95 96 g.fillRect(x, y, width, ht); 97 msg=false; 98 } 99 100 101 } 102 103 } 104 }