HFJ2 AppendixA

download HFJ2 AppendixA

of 10

Transcript of HFJ2 AppendixA

  • 8/8/2019 HFJ2 AppendixA

    1/10

    *ppendix A:Final Code Kitchen*

    Chris: groove2 revised

    NIgel:dance beat

    FinaLLy, the complete version 01 the BeatBox!

    It connects to a simple MusicServer so that you cansend an d receive beat patterns with other clients.

    this is a ne w appendix 649

    A-PDF Split DEMO : Purchase from www.A-PDF.com to remove the watermark

    http://www.a-pdf.com/?product-split-demohttp://www.a-pdf.com/?product-split-demo
  • 8/8/2019 HFJ2 AppendixA

    2/10

    final BeatBox code

    Final BeatBox client programMost of this code is the same as the code from the CodeKitchens in the previouschapters, so we don 't annotate the whole thing again. The new parts include:

    GUI - two new components are added for the text area that displays incomingmessages (actually a scrolling list) and the text field .

    NETWORKING - just like the SimpleChatClient in this chapter, the BeatBox nowconnects to the server and gets an input and output stream.

    THREADS - again, just like the SimpleChatClient, we start a 'reader' class thatkeeps looking for incoming messages from the server. But instead of just text, themessages coming in include TWO objects: the String message and the serializedArrayList (the thing that holds the state of all the checkboxes.)

    import j ava .awt .* ;import javax .swing .* ;import j a v a . i o . * ;i mp or t j av ax . sound. midi . *;import j a v a . u t i l .* ;import j ava .awt .even t .* ;import j ava . n e t . * ;i mp or t j av ax .s w in g . event .* ;

    publ ic c l a s s BeatBoxFinal

    JFrame theFrame;JPanel mainPanel ;J L i s t incomingList ;JTex tF ie ld userMessage;ArrayList checkboxList ;

    i n t nextNum;Vector l i s t Ve c t o r = new Vector() ;S t r i n g userName;ObjectOUtputStream o u t ;ObjectInputStream i n ;HashMap otherSeqsMap new HashMap( ) ;

    Sequencer sequencer;Sequence sequence;Sequence mySequence = n u l l ;Track t r a c k ;

    St r ing[ ] instrumentNames = { ~ B a s sDrum", ~ C l o s e dHi-Hat", ~ O p e nHi-Hat" ,"Acoust icSnare" , ~ C r a s hCymbal", ~ H a n dClap", ~ H i g hTom", ~ H i Bongo", ~ M a r a c a s " , ~ W h i s t l e "~ L o wConga " , ~ C o w b e l l " ,~ V i b r a s l a p " , ~ L o w - m i dTom" , ~ H i g hAqogo " , ~ O p e nHi Conga");

    i n t [ ] ins t ruments = {35 ,42 ,46 ,38 ,49 ,39 ,50 ,60 ,70 ,72 ,64 ,56 ,58 ,47 ,67 , 63) ;

    65 0 appen dix A

  • 8/8/2019 HFJ2 AppendixA

    3/10

    appendix A Final Code K itche n

    s t a t i c void main (Str ing[] args) (BeatBoxFinal() . s t a r tUp(args [O]) ; I I args[O] i s your user ID/screen name

    fI\ l .f \ J0 ~V -st v-ee Yl Yla",e"" - - - - - AdO. a t..o", ....aYlo-liYle a v - ~~ " , eY l 1 ; .ov- I

    c I ' 01 'ava 0eatB o l-f=iYlal thef=lash... '/.cl ....y e ID j [}

    publ icnew

    publ ic void s t a r t u p ( S t r i n g name) {userName = name;I I open connect ion to the s e r v e rt r y (

    S oc ke t s oc k = new Socket(" l27 .0 . 0 . l " , 4242);o u t = new ObjectOutputStream(sock.getOUtputStream(;i n = new ObjectInputStream(sock.getInputStream(;T hr ea d r em ot e = new Thread(new RemoteReader(;remote . s t a r t 0 ;catch(Except ion ex ) (

    Sys tem.out .p r in t ln ("couldn ' t connect - y o u ' l l have to play alone ." ) ;}setupMidi 0 ;buildGUI () ;

    I I c l ose s t a rt Up

    publ ic void buildGUI () ~ l A . 1tode, Y l o th i Y l ~Yle ." he v-e

    theFrame = new JFrame("Cyber BeatBox");BorderLayout l ayout = new BorderLayout() ;JPanel background = new JPanel( layout) ;background.setBorder(BorderFactory.createEmptyBorder(10,10,10,10;

    checkboxList = new ArrayList() ;

    Box buttonBox = new Box(BoxLayout.Y_AXIS);JButton s t a r t = new J B u t t o n ( " S t a r t " ) ;star t .addActionListener(new MyStar tLis tener ( ;but tonBox.add(s ta r t ) ;

    JButton s top = new JButton("Stop") ;stop.addActionListener(new MyStopLis tener ( ;but tonBox.add(stop);

    JButton upTempo = new JBut ton("Tempo Up") ;upTempo.addAct ionLis tener(new MyUpTempoListener(;buttonBox.add(upTempo);

    JButton downTempo = new JButton("Tempo Down") ;downTempo.addActionListener(new MyDownTempoListener(;buttonBox.add(downTempo) ;

    JButton s e n d l t = new JBut ton("sendI t " ) ;sendlt .addActionListener(new MySendLis tener ( ;buttonBox.add(sendIt) ;

    userMessage = new JTextF ie ld( ) ;

    yo u ar e h ere ~ 651

  • 8/8/2019 HFJ2 AppendixA

    4/10

    final BeatBox code

    but tonBox.add(userMessage) :

    Box namaBox ::; new Bo x (BoxLayout. 'i_AXIS) ifo r ( i n t i = 0; i < 16 ; i++) {

    nameBox. aeld(naw Labe l (i.nst%UmentNames [ i ] ;

    background.. a dd (Bord.erLayout . EAST , buttonBox) ibackground.. add (Bord.erLayou t . WEST, nameBox) ;

    theFrame. qetContentpane () . add. (background) ;GridLayout g r i d ' " new GridLayout(16,16);g r i d . aetVgap (1 ) ;gr id . se tHqap(2) :mai nP a ne l '" new . J i ' ane l (gr id) :background. add (Borde rLayou t . CENTER, UlA1nPanel);

    f o r ( i n t i '" 0; i < 256; i++) (JCheckBox c '" new JCheck.Box () ;c . s e t s e1ec t ed ( f a l s e ) ;checkboxList.add.(c) ;DIlU.nPanel. add. (c ) ;

    I I end loop

    theFrAmQ.aetBounds(50,50,300,300);theFrAmQ . pack () ;theFrame.se tVis ib le ( t rue) ;I I close buildGUI

    publ ic void. setUpMidi ()t r y (sequence r IS MidiSys tem . ge tSequence r () is e qu e nce r. open ( ) ;sequence IS ne w sequence (Saquence.PPQ,4) ;t r ack '" sequance .a rea teTrack( ) ;sequencer.setTempolnBPM(120);

    ca tch (Exception e) (e . p r in t s tackTrace () ; )

    I I close setUpMldi

    652 appendix. A

  • 8/8/2019 HFJ2 AppendixA

    5/10

    appendix A Final Co de Kitche n

    f o r ( i n t i = 0; i < 16; i++) {

    I I because t h i s s l o t should be empty i n the t r a c k

    t r a c k L i s t = new ArrayLis t( ) ;

    p u b l i c void bu i ldTrackAndStar t ( ) {ArrayList t r a c k L i s t = n u l l ;sequence . de le teTrack( t rack) ;t rack = sequence .c rea teTrack( ) ;

    I I t h i s w i l l hold t he i ns tr um en ts fo r eachh the t..het.k'ooi-tS

    '0 ' f I o \ ki \ ' \ ~t h Y " o ~t t to a\'\?J",M 0 kO ,t.kSJtel oYlO. , . . a Y Y M i ~ ~, c h l / ~Y lt koY" .o . Lto jtt "flt lC\'\0 " , o k i Y l ~the . 1 ~1 r ; , . ACTL.:'! oSi"i\'\stv-",,,,e\'\t ~ . o\e1'o, b",t It I S~ ) < L oY"el/io .lS

    . et,,\1 ..0"' , L Y"eteY" "IP ,T\oils 'S yY" ' r . t.hay"eY"s, so L' a ~ a i Y l .. the yyel/lOI.lSL LL f' "'\\ ei-y\aYlo"IOYl

    'fIoS 1\'\ to ~ e" "fie -tfo r ( i n t j = 0 ; j < 16; j++) { C o d e ~ lt t . . h e \ ' l S

    JCheckBox j c = (JCheckBox) checkboxLis t .ge t ( j + ( 1 6 * i ;i f ( j c . i sSe lec ted( (

    i n t ke y = i n s t r u m e n t s [ i ] ;t rackList .add(new I n t ege r (key ;

    e l s e {t r a c k L i s t . a d d ( n u l l ) ;}

    } I I c l o s e i n n e r l oo pmakeTracks{trackList) ;

    } I I c l o s e o u t e r l o o pt r ack .add(makeEvent{192 ,9 ,1 ,0 ,15 ; I I - so we always go to f u l l 16 b e a t st r y {

    sequencer.setSequence(sequence);sequencer . setLoopCount (sequencer. LOOP_CONTINUOUSLY) ;sequencer . s t a r t ( ) ;sequencer.setTempolnBPM{120);

    } catch(Except ion e) {e .pr in tS tackTrace( ) ;}} I I c l o s e me t h o d

    publ ic c l a s s MyStartLis tener implements Act ionLis tenerpubl ic void actionPerformed(ActionEvent a) {

    buildTrackAndStar t ( ) ;} I I c l o s e a c t i o n P e r f o rm e d

    II c l o se i n n e r c l as s

    publ ic c l a s s MyStopListener implements Act ionLis tenerpubl ic void actionPerformed(ActionEvent a) (

    sequencer . s top () ;} II c l o s e a c t i onP e r fo rmedII c l o s e i nne r c l a s s

    publ ic c l a s s MyUpTempoListener implements Act ionLis tenerpubl ic void actionPerformed(ActionEvent a) {

    f lo a t t em po F ac to r = sequencer.getTempoFactor() ;sequencer.setTempoFactorf loat) (tempoFactor * 1 . 0 3 ;

    } II c l o s e a c t i o nPer f o rmedII c l o se i n n e r c l a s s

    you a re here . 65 3

  • 8/8/2019 HFJ2 AppendixA

    6/10

    final BeatBox code

    publ ic c l a s s MyDownTempoListener ~ l e m e n t sAct ionLis tenerpubl ic void act ionPerformed(ActionEvent a) {

    f io at t em po F ac to r = sequencer .getTempoFactor() ;sequencer.setTempoFactorf ioat) (tempoFactor * . 9 7 ;

    publ ic c l a s s MySendListener implements Act ionLis tener (publ ic void act ionPerformed(ActionEvent a) {

    I I make an a r r a y l i s t o f j u s t the STATE o f th e checkboxesboolean[] checkboxState = new boolean[256] ;

    fo r ( i n t i = 0; i < 256; i++) {JCheckBox check = (JCheckBox)i f (check. isSelected( {

    checkboxState[ i ] = t r ue ;}

    }II c l os

    e l oopS t r i n g messageToSend = nu l l ;t r y {

    out .wri teObject(userName + nextNum++ + " . " + userMessage.getText( ;ou t .wr i t eObjec t (checkboxSta te ) ;

    catch(Exception ex ) {Sys tem.out .p r in t ln ("Sor ry dude. Could n ot send i t to th e s e r v e r. " ) ;

    }

    userMessage.setText(" " ) ;} I I c l o se a c t i onPer fo rm ed

    I I c l os e i nne r c l a s s

    publ ic c l a s s MyLis tSe lec t ionLis tener implements Lis tSe lec t ionLis tenerpubl ic void valueChanged(ListSelect ionEvent le ) {

    i f ( ! l e .getValueIsAdjust ing( {S tr in g s el ec te d = (Str ing) incomingList . ge t se lec tedValue( ) ;i f ( se lec ted != nul l ) (

    I I now go to th e map, an d change th e sequenceboolean[] se lec tedSta te = (boolean[]) otherSeqsMap.ge t ( se lec ted) ;changeSequence(selectedState) ;sequencer. s top( ) ;bui ldTrackAndSta r t ( ) ;

    }II c lose valueC ha nged

    I I c l os e i nner c l a s s

    65 4 appen dix A

  • 8/8/2019 HFJ2 AppendixA

    7/10

    appendix A Fin al C ode Kit chenpubl ic c l a s s RemoteReader implemen t s Runnable {

    boolean[] checkboxState = n u l l ;Str ing nameToShow = n u l l ;Objec t obj = n u l l ;publ ic v o id rune)

    {t r y {whi l e o b j = in . readObjec t ( != nul l ) {

    S y s t e m . o u t . p r i n t l n ( " g o t an o b j e c t fromSystem . o u t . p r i n t l n (ob j . g e t C l a s s ( ;Str ing nameT oShow = (Str ing) obj ;checkboxState = (boolean[]) in . readObjec t ( ) ;otherSeqsMap.put(nameToShow, checkboxState) ;l i s tVe c to r .add(nameToShow) ;incomingLis t . se tL is tData ( l i s tVec tor ) ;

    } I I c l ose wh i l ecatch(Exception ex ) {ex .pr in tS tackTrace( ) ;}

    I I c lose ru nI I c lose i n n e r c l a s s

    W ~ ~ I Ia ~ e s S 4( d e s e r i a J i ~ ){ h ~t : ill, lIIeread

    ~ ~ s s a g ealld.L e 1110 ob ie t L (t hetkb. ,;he Arra c: rs thethe J L ~ ~s t au v a ll A es f ~Ids+,0+ Boo/ea ll. J C t o ~ p .L I'l tidd .L JIS a 1;111 U Ohe n, ; . Add ' I,; 1;00+ the!:;ts p th il'l.9: 'lOlAk 1119 to a JL istfashioned Adata !Vetto : ~ pa VettorJList to rrayLisi) a ; 't.an oJd_

    .for wh t lAse thai. V e ~ khen t ~1 Jt hpubl ic c l a s s MyPlayMineLis tener implements Act ionLis tener { a to d isplay' .L as it's SOIA epubl ic vo i d a c t ionPerformed(Act ionEvent a) { III , ;h ~lisi.. r t ~

    i f (mySequence != nul l ) {sequence = mySequence ; I I r e s t o r e to my or ig ina l

    All the MIDI sh H is ~ u t t l ~the SaMe as itwas in the yYe'JiolAS'Jet-Slon.

    This I f t ~ t h o dis tailed h ts Ol f te t h i n ~.ft-Olftth I' i ~ he lASerselet ts

    c h e c k b o x S t a ~, n ~the patter: ;;.fh e /NI'j1hf;[)/ATE.LYe one .. ey selet te d.

    checkboxLis t .ge t ( i ) ;

    }} I I c l ose ac t i o n P e r f ormed

    I I c lose i n n e r c l a s s

    }I I c l os e l oo p

    I I c lose chang e Se quence

    publ ic void changeSequence(boolean[]f o r ( i n t i = 0; i < 256; i++) {

    JCheckBox check = (JCheckBox)i f (checkboxState[ i ]) {

    check . se tSe lec ted( t rue) ;e l s e {

    check . s e t S e l e c t e d ( f a l s e ) ;

    pu b l i c void makeTracks(ArrayLis t l i s t )I t e r a t o r i t = l i s t . i t e r a t o r ( ) ;f o r ( i n t i = 0; i < 16 ; i++) {

    I n t e g e r num = ( In teger ) i t . n e x t ( ) ;i f (num != nul l ) {

    i n t numKey = num.intV a lue( ) ;t rack.add(makeEvent(144 ,9 ,numKey, 100, i ;t r a c k .add(makeEvent(128,9 ,numKey,100, i + 1 ;

    }

    } I I c lo se lo opI I c l os e makeTrac ks()

    you ar e he re . 65 5

    ._ - -- - - - - - - -

  • 8/8/2019 HFJ2 AppendixA

    8/10

    final BeatBox code

    publ ic MidiEvent makeEvent( int comd, i n t chan, i n t one, i n t two, i n t t i c k ) {MidiEvent event = nu l l ;t r y {

    ShortMessage a = new ShortMessage();a . setMessage (comd, chan, one, tw o);even t = new MidiEvent(a, t i c k ) ;

    }ca tch (Exception e} { } \ i ~ et he l as t ~ e ' f " s i ( ) ' l \re turn event ; N o t \ \ ' ' ' ~"eVl J ~ t

    } I I c l o se rnakeEvent

    } I I c l o s e c l a s s

    ~ y o u r p e n C i i

    What are some of the ways you can improve this program?

    Hereare a few ideas to get you started :

    1)Once you select a pattern, whatever current pattern was playing is blownaway . If that was a new pattern you were working on (or a modification ofanother one), you're ou t of luck . You might want to pop up a dialog box thatasks th e userif he'd like to savethe current pattern .

    2)If you fail to type in a command-line argument, you just get an exceptionwhen you run it! Put something in the ma in method that checksto see ifyou've passed in a command-line argument. If the use r doesn't supply one,either pick a default or print out a message that saysthey need to run itagain, bu t this t ime with an argumentfor their screen name.

    3)It might be nice to havea feature where you can click a button and itwill generate a random pattern for you . You might hi t on one you really like.Better yet, have another feature that lets you load in existing 'foundation'patterns, like one for jazz, rock, reggae, etc. that the usercan add to.

    You can find existing patterns on the Head First Javaweb start.

    656 ap p en di x A

  • 8/8/2019 HFJ2 AppendixA

    9/10

    appendix A Fina l Cod e Kitc he n

    Final BeatBox server programMost of this code is identical to the SimpleChatServer we made in the

    Networking and Threads chapter. The only difference , in fact, is that this serverreceives, and then re-sends, two serialized objects instead of a plain String(although one of the serialized objects happens to be a String).

    import j a v a . i o . * ;import j a v a . n e t . * ;import j a v a . u t i l . * ;

    publ ic c l a s s MusicServer

    ArrayList cl ientOutputStreams;

    p u b l i c s t a t i c void main (Str ing[] args) {new MusicServer() . go ( ) ;

    publ ic c l a s s ClientHandler implements Runnable {

    Object lnputStream i n ;Socket c l ien tSocke t ;

    publ ic Cl ien tHand le r (Socke t socket ) (t r y {

    c l ien tSocke t = socke t ;i n = new Object lnputStream(cl ientSocket . g e t l n p u t S t r e a m ( ;

    catch(Except ion ex ) (ex .p r in tS tackTrace( ) ;}} I I c l os e co n s t ru c t o r

    publ ic void ru n {} {Object 02 = n u l l ;Object 01 = nul l ;

    t r y {

    while ((01 = in . readObject( != nul l ) (

    02 = i n . r eadObjec t ( ) ;

    System . o u t . p r i n t l n ( " r e a d two objec t s ") ;t el lE v er y on e (0 1 , 0 2 );I I c l os e wh il e

    catch(Except ion ex ) (ex .p r in tS tackTrace( ) ;}I I c l os e ru n

    I I c l o s e i n n e r c l a s s

    yo u a re h e re ~ 65 7

  • 8/8/2019 HFJ2 AppendixA

    10/10

    final BeatBox code

    p u b l i c void qo() {cl ientOutputStreams = new ArrayLis t() ;

    t r y {ServerSocket serverSock = new ServerSocket(4242);

    while ( t rue) {Socket c l ien tSocke t = se rverSock .accep t ( ) ;ObjectOutputStream ou t = new ObjectOutputStream(cl ientSocket .qetOutputStream(cl ientOutputStreams.add(out) ;

    Thread t = new Thread(new Cl ien tHandle r (c l i en tSocke t ;t . s t a r t ( ) ;

    Sys tem.out .p r in t ln ("qo t a connect ion " ) ;}

    }catch(Except ion ex ) {ex .pr in tS tackTrace( ) ;

    }I I c lose go

    p u b l i c void t e l lEveryone(Objec t on e , Object two)I t e r a t o r i t = c l i e n t O u t p u t S t r e a m s . i t e r a t o r ( ) ;w h i l e ( i t .hasNext( {

    t r y {ObjectOutputStream o u t = (ObjectOutputStream) i t . n e x t ( ) ;out .wri teObject(one) ;out .wr i t eObjec t ( two) ;

    }catch(Except ion ex ) {ex.printStackTrace() ;}

    I I c lose t e l l Everyone

    } I I c lose class

    658 appen dix A