├── AppendixA ├── BeatBoxFinal$MyDownTempoListener.class ├── BeatBoxFinal$MyListSelectionListener.class ├── BeatBoxFinal$MySendListener.class ├── BeatBoxFinal$MyStartListener.class ├── BeatBoxFinal$MyStopListener.class ├── BeatBoxFinal$MyUpTempoListener.class ├── BeatBoxFinal$RemoteReader.class ├── BeatBoxFinal.class ├── BeatBoxFinal.java ├── MusicServer$ClientHandler.class ├── MusicServer.class └── MusicServer.java ├── README.md ├── chap01 ├── BeerSong.class ├── BeerSong.java ├── PhraseOMatic.class └── PhraseOMatic.java ├── chap02 ├── GameLauncher.class ├── GameLauncher.java ├── GuessGame.class ├── GuessGame.java ├── Player.class └── Player.java ├── chap03 ├── Dog.class └── Dog.java ├── chap04 ├── Foo.class ├── Foo.java ├── GoodDog.class ├── GoodDogTestDrive.class ├── GoodDogTestDrive.java ├── PoorDog.class ├── PoorDogTestDrive.class └── PoorDogTestDrive.java ├── chap05 ├── Game.class ├── Game.java ├── GameHelper.class ├── GameHelper.java ├── SimpleDotCom.class ├── SimpleDotCom.java ├── SimpleDotComTester.class └── SimpleDotComTester.java ├── chap06 ├── DotCom.class ├── DotCom.java ├── DotComBust.class └── DotComBust.java ├── chap07 ├── Boat.class ├── Rowboat.class ├── Sailboat.class ├── TestBoat.class └── TestBoat.java ├── chap08 ├── Acts.class ├── Clowns.class ├── Nose.class ├── Of76.class ├── Of76.java └── Picasso.class ├── chap09 ├── RetentionBot.class ├── SimUnit.class ├── TestLifeSupportSim.class ├── TestLifeSupportSim.java ├── V2Radiator.class └── V3Radiator.class ├── chap10 ├── FullMoons.class └── FullMoons.java ├── chap11 ├── MiniMiniMusicApp.class ├── MiniMiniMusicApp.java ├── MiniMiniMusicCmdLine.class └── MiniMiniMusicCmdLine.java ├── chap12 ├── Animate$MyDrawP.class ├── Animate.class ├── Animate.java ├── MiniMusicPlayer3$MyDrawPanel.class ├── MiniMusicPlayer3.class ├── MiniMusicPlayer3.java ├── MyDrawPanel.class ├── SimpleAnimation$MyDrawPanel.class ├── SimpleAnimation.class ├── SimpleAnimation.java ├── TwoButtons$ColorButtonListener.class ├── TwoButtons$LabelButtonListener.class ├── TwoButtons.class └── TwoButtons.java ├── chap13 ├── BeatBox$MyDownTempoListener.class ├── BeatBox$MyStartListener.class ├── BeatBox$MyStopListener.class ├── BeatBox$MyUpTempoListener.class ├── BeatBox.class └── BeatBox.java ├── chap14 ├── BeatBoxSaveOnly$MyDownTempoListener.class ├── BeatBoxSaveOnly$MyReadInListener.class ├── BeatBoxSaveOnly$MySendListener.class ├── BeatBoxSaveOnly$MyStartListener.class ├── BeatBoxSaveOnly$MyStopListener.class ├── BeatBoxSaveOnly$MyUpTempoListener.class ├── BeatBoxSaveOnly.class ├── BeatBoxSaveOnly.java ├── DungeonGame.class ├── DungeonTest.class ├── DungeonTest.java ├── GameCharacter.class ├── GameCharacter.java ├── GameSaverTest.class ├── GameSaverTest.java ├── QuizCard.class ├── QuizCard.java ├── QuizCardBuilder$NewMenuListener.class ├── QuizCardBuilder$NextCardListener.class ├── QuizCardBuilder$SaveMenuListener.class ├── QuizCardBuilder.class ├── QuizCardBuilder.java ├── QuizCardReader$NextCardListener.class ├── QuizCardReader$OpenMenuListener.class ├── QuizCardReader.class └── QuizCardReader.java ├── chap15 ├── BankAccount.class ├── DailyAdviceClient.class ├── DailyAdviceClient.java ├── DailyAdviceServer.class ├── DailyAdviceServer.java ├── MyRunnable.class ├── MyRunnable.java ├── RunThreads.class ├── RunThreads.java ├── RyanAndMonicaJob.class ├── RyanAndMonicaJob.java ├── SimpleChatClient$IncomingReader.class ├── SimpleChatClient$SendButtonListener.class ├── SimpleChatClient.class ├── SimpleChatClient.java ├── SimpleChatClientA$SendButtonListener.class ├── SimpleChatClientA.class ├── SimpleChatClientA.java ├── VerySimpleChatServer$ClientHandler.class ├── VerySimpleChatServer.class └── VerySimpleChatServer.java ├── chap16 ├── Jukebox1.class ├── Jukebox1.java ├── Jukebox3.class ├── Jukebox3.java ├── Jukebox5$ArtistCompare.class ├── Jukebox5.class ├── Jukebox5.java ├── Jukebox6.class ├── Jukebox6.java ├── Jukebox8.class ├── Jukebox8.java ├── Song.class └── Song.java └── chap18 ├── DayOfTheWeekService$DoItListener.class ├── DayOfTheWeekService.class ├── DayOfTheWeekService.java ├── DiceService$RollEmListener.class ├── DiceService.class ├── DiceService.java ├── KathyServlet.class ├── KathyServlet.java ├── MiniMusicService$MyDrawPanel.class ├── MiniMusicService$PlayItListener.class ├── MiniMusicService.class ├── MiniMusicService.java ├── PhraseOMatic2.class ├── PhraseOMatic2.java ├── Service.class ├── Service.java ├── ServiceBrowser$MyListListener.class ├── ServiceBrowser.class ├── ServiceBrowser.java ├── ServiceServer.class ├── ServiceServer.java ├── ServiceServerImpl.class └── ServiceServerImpl.java /AppendixA/BeatBoxFinal$MyDownTempoListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/AppendixA/BeatBoxFinal$MyDownTempoListener.class -------------------------------------------------------------------------------- /AppendixA/BeatBoxFinal$MyListSelectionListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/AppendixA/BeatBoxFinal$MyListSelectionListener.class -------------------------------------------------------------------------------- /AppendixA/BeatBoxFinal$MySendListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/AppendixA/BeatBoxFinal$MySendListener.class -------------------------------------------------------------------------------- /AppendixA/BeatBoxFinal$MyStartListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/AppendixA/BeatBoxFinal$MyStartListener.class -------------------------------------------------------------------------------- /AppendixA/BeatBoxFinal$MyStopListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/AppendixA/BeatBoxFinal$MyStopListener.class -------------------------------------------------------------------------------- /AppendixA/BeatBoxFinal$MyUpTempoListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/AppendixA/BeatBoxFinal$MyUpTempoListener.class -------------------------------------------------------------------------------- /AppendixA/BeatBoxFinal$RemoteReader.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/AppendixA/BeatBoxFinal$RemoteReader.class -------------------------------------------------------------------------------- /AppendixA/BeatBoxFinal.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/AppendixA/BeatBoxFinal.class -------------------------------------------------------------------------------- /AppendixA/BeatBoxFinal.java: -------------------------------------------------------------------------------- 1 | package AppendixA; 2 | // chapter 14 3 | 4 | import java.awt.*; 5 | import javax.swing.*; 6 | import javax.swing.event.ListSelectionEvent; 7 | import javax.swing.event.ListSelectionListener; 8 | 9 | import java.io.*; 10 | import javax.sound.midi.*; 11 | import java.util.*; 12 | import java.awt.event.*; 13 | import java.net.*; 14 | 15 | 16 | public class BeatBoxFinal { // implements MetaEventListener 17 | 18 | JPanel mainPanel; 19 | JList incomingList; 20 | JTextField userMessage; 21 | ArrayList checkboxList; 22 | int nextNum; 23 | ObjectInputStream in; 24 | ObjectOutputStream out; 25 | Vector listVector = new Vector(); 26 | String userName ; 27 | HashMap otherSeqsMap = new HashMap(); 28 | Sequencer sequencer; 29 | Sequence sequence; 30 | Sequence mySequence = null; 31 | Track track; 32 | JFrame theFrame; 33 | 34 | String[] instrumentNames = {"Bass Drum", "Closed Hi-Hat", 35 | "Open Hi-Hat","Acoustic Snare", "Crash Cymbal", "Hand Clap", 36 | "High Tom", "Hi Bongo", "Maracas", "Whistle", "Low Conga", 37 | "Cowbell", "Vibraslap", "Low-mid Tom", "High Agogo", 38 | "Open Hi Conga"}; 39 | int[] instruments = {35,42,46,38,49,39,50,60,70,72,64,56,58,47,67,63}; 40 | 41 | 42 | public static void main (String[] args) { 43 | new BeatBoxFinal().startUp(args[0]); 44 | } 45 | 46 | public void startUp(String name) { 47 | userName = name; 48 | try { 49 | Socket sock = new Socket("127.0.0.1", 4242); 50 | out = new ObjectOutputStream(sock.getOutputStream()); 51 | in = new ObjectInputStream(sock.getInputStream()); 52 | Thread remote = new Thread(new RemoteReader()); 53 | remote.start(); 54 | } 55 | catch (Exception ex) { 56 | System.out.println("couldn't connect - you'll have to play alone."); 57 | } 58 | setUpMidi(); 59 | buildGUI(); 60 | } 61 | 62 | public void buildGUI() { 63 | theFrame = new JFrame("Cyber BeatBox"); 64 | theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 65 | BorderLayout layout = new BorderLayout(); 66 | JPanel background = new JPanel(layout); 67 | background.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); 68 | 69 | checkboxList = new ArrayList(); 70 | Box buttonBox = new Box(BoxLayout.Y_AXIS); 71 | 72 | JButton start = new JButton("Start"); 73 | start.addActionListener(new MyStartListener()); 74 | buttonBox.add(start); 75 | 76 | 77 | JButton stop = new JButton("Stop"); 78 | stop.addActionListener(new MyStopListener()); 79 | buttonBox.add(stop); 80 | 81 | JButton upTempo = new JButton("Tempo Up"); 82 | upTempo.addActionListener(new MyUpTempoListener()); 83 | buttonBox.add(upTempo); 84 | 85 | JButton downTempo = new JButton("Tempo Down"); 86 | downTempo.addActionListener(new MyDownTempoListener()); 87 | buttonBox.add(downTempo); 88 | 89 | JButton sendIt = new JButton("sendIt"); 90 | sendIt.addActionListener(new MySendListener()); 91 | buttonBox.add(sendIt); 92 | 93 | 94 | JButton saveIt = new JButton("Serialize It"); // new button 95 | saveIt.addActionListener(new MySendListener()); 96 | buttonBox.add(saveIt); 97 | 98 | userMessage = new JTextField(); 99 | buttonBox.add(userMessage); 100 | 101 | incomingList = new JList(); 102 | incomingList.addListSelectionListener(new MyListSelectionListener()); 103 | incomingList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 104 | JScrollPane theList = new JScrollPane(incomingList); 105 | buttonBox.add(theList); 106 | incomingList.setListData(listVector); 107 | 108 | Box nameBox = new Box(BoxLayout.Y_AXIS); 109 | for (int i = 0; i < 16; i++) { 110 | nameBox.add(new Label(instrumentNames[i])); 111 | } 112 | 113 | background.add(BorderLayout.EAST, buttonBox); 114 | background.add(BorderLayout.WEST, nameBox); 115 | 116 | theFrame.getContentPane().add(background); 117 | 118 | GridLayout grid = new GridLayout(16,16); 119 | grid.setVgap(1); 120 | grid.setHgap(2); 121 | mainPanel = new JPanel(grid); 122 | background.add(BorderLayout.CENTER, mainPanel); 123 | 124 | 125 | for (int i = 0; i < 256; i++) { 126 | JCheckBox c = new JCheckBox(); 127 | c.setSelected(false); 128 | checkboxList.add(c); 129 | mainPanel.add(c); 130 | } // end loop 131 | 132 | theFrame.setBounds(50,50,300,300); 133 | theFrame.pack(); 134 | theFrame.setVisible(true); 135 | } // close method 136 | 137 | 138 | public void setUpMidi() { 139 | try { 140 | sequencer = MidiSystem.getSequencer(); 141 | sequencer.open(); 142 | // sequencer.addMetaEventListener(this); 143 | sequence = new Sequence(Sequence.PPQ,4); 144 | track = sequence.createTrack(); 145 | sequencer.setTempoInBPM(120); 146 | 147 | } catch(Exception e) {e.printStackTrace();} 148 | } // close method 149 | 150 | public void buildTrackAndStart() 151 | { 152 | // this will hold the instruments for each vertical column, 153 | // in other words, each tick (may have multiple instruments) 154 | ArrayList trackList = null; 155 | 156 | sequence.deleteTrack(track); 157 | track = sequence.createTrack(); 158 | 159 | 160 | for (int i = 0; i < 16; i++){ 161 | trackList = new ArrayList(); 162 | for (int j = 0; j < 16; j++){ 163 | JCheckBox jc = (JCheckBox) checkboxList.get(j + (16 * i)); 164 | if (jc.isSelected()){ 165 | int key = instruments[i]; 166 | trackList.add(key); 167 | } 168 | else 169 | { 170 | trackList.add(null); 171 | } 172 | } // close inner 173 | 174 | makeTracks(trackList); 175 | } // close outer 176 | 177 | track.add(makeEvent(192,9,1,0,15)); // - so we always go to full 16 beats 178 | 179 | 180 | 181 | try { 182 | 183 | sequencer.setSequence(sequence); 184 | sequencer.setLoopCount(sequencer.LOOP_CONTINUOUSLY); 185 | sequencer.start(); 186 | sequencer.setTempoInBPM(120); 187 | } catch(Exception e) {e.printStackTrace();} 188 | 189 | } // close method 190 | 191 | //============================================================== inner class listeners 192 | 193 | public class MyStartListener implements ActionListener { 194 | public void actionPerformed(ActionEvent a) { 195 | buildTrackAndStart(); 196 | } 197 | } 198 | 199 | public class MyStopListener implements ActionListener { 200 | public void actionPerformed(ActionEvent a) { 201 | sequencer.stop(); 202 | } 203 | } 204 | 205 | public class MyUpTempoListener implements ActionListener { 206 | public void actionPerformed(ActionEvent a) { 207 | float tempoFactor = sequencer.getTempoFactor(); 208 | sequencer.setTempoFactor((float)(tempoFactor * 1.03)); 209 | } 210 | } 211 | 212 | public class MyDownTempoListener implements ActionListener { 213 | public void actionPerformed(ActionEvent a) { 214 | float tempoFactor = sequencer.getTempoFactor(); 215 | sequencer.setTempoFactor((float)(tempoFactor * .97)); 216 | } 217 | } 218 | 219 | public class MySendListener implements ActionListener { // new - save 220 | public void actionPerformed(ActionEvent a) { 221 | // make an arraylist of just the STATE of the checkboxes 222 | boolean[] checkboxState = new boolean[256]; 223 | 224 | for (int i = 0; i < 256; i++) { 225 | JCheckBox check = (JCheckBox) checkboxList.get(i); 226 | if (check.isSelected()) { 227 | checkboxState[i] = true; 228 | } 229 | } 230 | 231 | try { 232 | out.writeObject(userName + nextNum++ + ": " + userMessage.getText()); 233 | out.writeObject(checkboxState); 234 | } catch(Exception ex) { 235 | ex.printStackTrace(); 236 | System.out.println("sorry dude. Could not send it to the server"); 237 | } 238 | 239 | } // close method 240 | } // close inner class 241 | 242 | public class MyListSelectionListener implements ListSelectionListener { 243 | public void valueChanged(ListSelectionEvent le) { 244 | if (!le.getValueIsAdjusting()) { 245 | String selected = (String) incomingList.getSelectedValue(); 246 | if (selected != null) { 247 | boolean[] selectedState = (boolean[]) otherSeqsMap.get(selected); 248 | changeSequence(selectedState); 249 | sequencer.stop(); 250 | buildTrackAndStart(); 251 | } 252 | } 253 | } 254 | } 255 | 256 | public class RemoteReader implements Runnable { 257 | boolean[] checkboxState = null; 258 | String nameToShow = null; 259 | Object obj = null; 260 | 261 | public void run() { 262 | try { 263 | while ((obj=in.readObject()) != null) { 264 | System.out.println("got an object from server"); 265 | System.out.println(obj.getClass()); 266 | String nameToShow = (String) obj; 267 | checkboxState = (boolean[]) in.readObject(); 268 | otherSeqsMap.put(nameToShow, checkboxState); 269 | listVector.add(nameToShow); 270 | incomingList.setListData(listVector); 271 | } 272 | }catch (Exception e) { e.printStackTrace(); } 273 | } 274 | } 275 | 276 | 277 | //============================================================== 278 | 279 | public void changeSequence(boolean[] checkboxState) { 280 | for (int i = 0; i < 256; i++) { 281 | JCheckBox check = (JCheckBox) checkboxList.get(i); 282 | if (checkboxState[i]) { 283 | check.setSelected(true); 284 | } 285 | else 286 | { 287 | check.setSelected(false); 288 | } 289 | } 290 | } 291 | 292 | public void makeTracks(ArrayList list) { 293 | Iterator it = list.iterator(); 294 | for (int i = 0; i < 16; i++) { 295 | Integer num = (Integer) it.next(); 296 | if (num != null) { 297 | int numKey = num.intValue(); 298 | track.add(makeEvent(144, 9, numKey, 100, i)); 299 | track.add(makeEvent(128, 9, numKey, 100, i+1)); 300 | } 301 | } 302 | } 303 | 304 | 305 | 306 | public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) { 307 | MidiEvent event = null; 308 | try { 309 | ShortMessage a = new ShortMessage(); 310 | a.setMessage(comd, chan, one, two); 311 | event = new MidiEvent(a, tick); 312 | 313 | }catch(Exception e) { } 314 | return event; 315 | } 316 | } 317 | 318 | -------------------------------------------------------------------------------- /AppendixA/MusicServer$ClientHandler.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/AppendixA/MusicServer$ClientHandler.class -------------------------------------------------------------------------------- /AppendixA/MusicServer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/AppendixA/MusicServer.class -------------------------------------------------------------------------------- /AppendixA/MusicServer.java: -------------------------------------------------------------------------------- 1 | package AppendixA; 2 | import java.io.*; 3 | import java.net.*; 4 | import java.util.*; 5 | 6 | 7 | public class MusicServer 8 | { 9 | ArrayList clientOutputStreams; 10 | 11 | public static void main(String[] args) { 12 | new MusicServer().go(); 13 | } 14 | 15 | public class ClientHandler implements Runnable { 16 | ObjectInputStream in; 17 | Socket sock; 18 | 19 | public ClientHandler(Socket clientSOcket) { 20 | try { 21 | sock = clientSOcket; 22 | in = new ObjectInputStream(sock.getInputStream()); 23 | 24 | } catch (Exception ex) { ex.printStackTrace(); } 25 | } 26 | 27 | public void run() { 28 | Object o1; 29 | Object o2; 30 | try { 31 | while ((o1 = in.readObject()) != null) { 32 | o2 = in.readObject(); 33 | System.out.println("read two objects"); 34 | tellEveryone(o1, o2); 35 | } 36 | } catch (Exception ex) { ex.printStackTrace(); } 37 | } 38 | } 39 | 40 | 41 | 42 | public void go() { 43 | clientOutputStreams = new ArrayList(); 44 | try { 45 | ServerSocket serverSock = new ServerSocket(4242); 46 | while(true) { 47 | Socket clientSocket = serverSock.accept(); 48 | ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream()); 49 | clientOutputStreams.add(out); 50 | 51 | Thread t = new Thread(new ClientHandler(clientSocket)); 52 | t.start(); 53 | System.out.println("got a connection"); 54 | } 55 | } catch (Exception ex) { ex.printStackTrace(); } 56 | } 57 | 58 | public void tellEveryone(Object one, Object two) { 59 | Iterator it = clientOutputStreams.iterator(); 60 | while (it.hasNext()) { 61 | try { 62 | ObjectOutputStream out = (ObjectOutputStream) it.next(); 63 | out.writeObject(one); 64 | out.writeObject(two); 65 | } catch (Exception ex) { ex.printStackTrace(); } 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Head-First-Java 2 | Code for Head First Java 3 | -------------------------------------------------------------------------------- /chap01/BeerSong.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap01/BeerSong.class -------------------------------------------------------------------------------- /chap01/BeerSong.java: -------------------------------------------------------------------------------- 1 | package chap01; 2 | 3 | public class BeerSong { 4 | public static void main(String[] args) { 5 | int beerNum = 99; 6 | String word = "bottles"; 7 | while (beerNum > 0) 8 | { 9 | if (beerNum == 1) 10 | { 11 | word = "bottle"; 12 | } 13 | System.out.println(beerNum + " " + word + " of beer on the wall"); 14 | System.out.println(beerNum + " " + word + " of beer"); 15 | System.out.println("Take one down."); 16 | System.out.println("Pass it around."); 17 | beerNum = beerNum - 1; 18 | if (beerNum > 0) 19 | { 20 | System.out.println(beerNum + " " + word + " of beer on the wall"); 21 | } 22 | else 23 | { 24 | System.out.println("No more bottles of beer on the wall"); 25 | } 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /chap01/PhraseOMatic.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap01/PhraseOMatic.class -------------------------------------------------------------------------------- /chap01/PhraseOMatic.java: -------------------------------------------------------------------------------- 1 | package chap01; 2 | 3 | public class PhraseOMatic { 4 | public static void main(String[] args) { 5 | String[] wordListOne = {"24/7", "multi-Tier", "30,000 foot", "B-to-B", 6 | "win-win", "front-end", "web-based", "pervasive", "smart", "six-sigma", 7 | "critical-path", "dynamic"}; 8 | String[] wordListTwo = {"empowered", "sticky", "value-added", "oriented", "centric", 9 | "distributed", "clustered", "branded", "outside-the-box", "positioned", "networked", 10 | "focused", "leveraged", "aligned", "targeted", "shared", "cooperative", "accelerated"}; 11 | String[] wordListThree = {"process", "tipping-point", "solution", "architecture", "core competency", 12 | "strategy", "mindshare", "portal", "space", "vision", "paradigm", "mission"}; 13 | int oneLength = wordListOne.length; 14 | int twoLength = wordListTwo.length; 15 | int threeLength = wordListThree.length; 16 | int rand1 = (int) (Math.random() * oneLength); 17 | int rand2 = (int) (Math.random() * twoLength); 18 | int rand3 = (int) (Math.random() * threeLength); 19 | 20 | String phrase = wordListOne[rand1] + " " + wordListTwo[rand2] + " " + wordListThree[rand3]; 21 | System.out.println("What we need is a " + phrase); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /chap02/GameLauncher.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap02/GameLauncher.class -------------------------------------------------------------------------------- /chap02/GameLauncher.java: -------------------------------------------------------------------------------- 1 | package chap02; 2 | 3 | public class GameLauncher { 4 | public static void main (String[] args) { 5 | GuessGame game = new GuessGame(); 6 | game.startGame(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /chap02/GuessGame.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap02/GuessGame.class -------------------------------------------------------------------------------- /chap02/GuessGame.java: -------------------------------------------------------------------------------- 1 | package chap02; 2 | 3 | public class GuessGame { 4 | 5 | Player p1; 6 | Player p2; 7 | Player p3; 8 | 9 | public void startGame() { 10 | p1 = new Player(); 11 | p2 = new Player(); 12 | p3 = new Player(); 13 | int guessp1 = 0; 14 | int guessp2 = 0; 15 | int guessp3 = 0; 16 | boolean p1isRight = false; 17 | boolean p2isRight = false; 18 | boolean p3isRight = false; 19 | int targetNumber = (int) (Math.random() * 10); 20 | System.out.println("I'm thinking of a number between 0 and 9..."); 21 | while(true) { 22 | System.out.println("Number to guess is " + targetNumber); 23 | 24 | p1.guess(); 25 | p2.guess(); 26 | p3.guess(); 27 | 28 | guessp1 = p1.number; 29 | System.out.println("Player one guessed " + guessp1); 30 | guessp2 = p2.number; 31 | System.out.println("Player two guessed " + guessp2); 32 | guessp3 = p3.number; 33 | System.out.println("Player three guessed " + guessp3); 34 | 35 | if (guessp1 == targetNumber) { 36 | p1isRight = true; 37 | } 38 | if (guessp2 == targetNumber) { 39 | p2isRight = true; 40 | } 41 | if (guessp3 == targetNumber) { 42 | p3isRight = true; 43 | } 44 | 45 | if (p1isRight || p2isRight || p3isRight) 46 | { 47 | System.out.println("We have a winner!"); 48 | System.out.println("Player one got it right? " + p1isRight); 49 | System.out.println("Player two got it right? " + p2isRight); 50 | System.out.println("Player three got it right? " + p3isRight); 51 | System.out.println("Game is over"); 52 | break; 53 | } 54 | else 55 | { 56 | System.out.println("Players will have to try again."); 57 | } 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /chap02/Player.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap02/Player.class -------------------------------------------------------------------------------- /chap02/Player.java: -------------------------------------------------------------------------------- 1 | package chap02; 2 | 3 | public class Player { 4 | int number = 0; 5 | public void guess() 6 | { 7 | number = (int) (Math.random() * 10); 8 | System.out.println("I'm guessing " + number); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /chap03/Dog.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap03/Dog.class -------------------------------------------------------------------------------- /chap03/Dog.java: -------------------------------------------------------------------------------- 1 | package chap03; 2 | 3 | public class Dog { 4 | String name; 5 | public static void main(String[] args) { 6 | Dog dog1 = new Dog(); 7 | dog1.bark(); 8 | dog1.name = "Bart"; 9 | 10 | Dog[] myDogs = new Dog[3]; 11 | myDogs[0] = new Dog(); 12 | myDogs[1] = new Dog(); 13 | myDogs[2] = dog1; 14 | 15 | myDogs[0].name = "Fred"; 16 | myDogs[1].name = "Marge"; 17 | 18 | System.out.print("last don't name is "); 19 | System.out.println(myDogs[2].name); 20 | 21 | int x = 0; 22 | while (x < myDogs.length) { 23 | myDogs[x].bark(); 24 | x = x+1; 25 | } 26 | } 27 | public void bark() { 28 | System.out.println(name + " says Ruff!"); 29 | } 30 | 31 | public void eat() { } 32 | 33 | public void chaseCat() { } 34 | } 35 | -------------------------------------------------------------------------------- /chap04/Foo.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap04/Foo.class -------------------------------------------------------------------------------- /chap04/Foo.java: -------------------------------------------------------------------------------- 1 | package chap04; 2 | 3 | 4 | //this shouldn't compile 5 | public class Foo { 6 | public void go() { 7 | int x =0; //added initialization after verified that it doesn't compile 8 | // without it -Tyler Boone 9 | int z = x + 3; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /chap04/GoodDog.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap04/GoodDog.class -------------------------------------------------------------------------------- /chap04/GoodDogTestDrive.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap04/GoodDogTestDrive.class -------------------------------------------------------------------------------- /chap04/GoodDogTestDrive.java: -------------------------------------------------------------------------------- 1 | package chap04; 2 | 3 | public class GoodDogTestDrive { 4 | public static void main(String[] args) 5 | { 6 | GoodDog one = new GoodDog(); 7 | one.setSize(70); 8 | GoodDog two = new GoodDog(); 9 | two.setSize(8); 10 | System.out.println("Dog one: " + one.getSize()); 11 | System.out.println("Dog two: " + two.getSize()); 12 | one.bark(); 13 | two.bark(); 14 | } 15 | } 16 | 17 | class GoodDog 18 | { 19 | private int size; 20 | public int getSize() { return size;} 21 | public void setSize(int s) { 22 | size = s; 23 | } 24 | 25 | void bark() { 26 | if (size > 60) { 27 | System.out.println("Wooof! Wooof!"); 28 | } else if (size > 60) { 29 | System.out.println("Ruff! Ruff!"); 30 | } else { 31 | System.out.println("Yip! Yip!"); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /chap04/PoorDog.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap04/PoorDog.class -------------------------------------------------------------------------------- /chap04/PoorDogTestDrive.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap04/PoorDogTestDrive.class -------------------------------------------------------------------------------- /chap04/PoorDogTestDrive.java: -------------------------------------------------------------------------------- 1 | package chap04; 2 | 3 | public class PoorDogTestDrive { 4 | public static void main(String[] args) 5 | { 6 | PoorDog one = new PoorDog(); 7 | System.out.println("Dog size is " + one.getSize()); 8 | System.out.println("Dog name is " + one.getName()); 9 | } 10 | } 11 | 12 | class PoorDog 13 | { 14 | private int size; 15 | private String name; 16 | public int getSize() { return size;} 17 | public String getName() { return name;} 18 | } 19 | -------------------------------------------------------------------------------- /chap05/Game.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap05/Game.class -------------------------------------------------------------------------------- /chap05/Game.java: -------------------------------------------------------------------------------- 1 | package chap05; 2 | 3 | import helpers.GameHelper; 4 | 5 | import java.util.Scanner; 6 | 7 | public class Game { 8 | public static void main(String[] args) 9 | { 10 | int numOfGuesses = 0; 11 | GameHelper helper = new GameHelper(); 12 | 13 | SimpleDotCom theDotCom = new SimpleDotCom(); 14 | int randomNum = (int) (Math.random() * 5); 15 | 16 | int[] locations = {randomNum, randomNum+1, randomNum+2}; 17 | theDotCom.setLocationCells(locations); 18 | boolean isAlive = true; 19 | while (isAlive == true) 20 | { 21 | String guess = helper.getUserInput("enter a number"); 22 | String result = theDotCom.checkYourself(guess); 23 | numOfGuesses++; 24 | if (result.equals("kill")) { 25 | isAlive = false; 26 | System.out.println("You took " + numOfGuesses + " guesses"); 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /chap05/GameHelper.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap05/GameHelper.class -------------------------------------------------------------------------------- /chap05/GameHelper.java: -------------------------------------------------------------------------------- 1 | package chap05; 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | public class GameHelper { 7 | 8 | private static final String alphabet = "abcdefg"; 9 | private int gridLength = 7; 10 | private int gridSize = 49; 11 | private int [] grid = new int[gridSize]; 12 | private int comCount = 0; 13 | 14 | 15 | public String getUserInput(String prompt) { 16 | String inputLine = null; 17 | System.out.print(prompt + " "); 18 | try { 19 | BufferedReader is = new BufferedReader( 20 | new InputStreamReader(System.in)); 21 | inputLine = is.readLine(); 22 | if (inputLine.length() == 0 ) return null; 23 | } catch (IOException e) { 24 | System.out.println("IOException: " + e); 25 | } 26 | return inputLine.toLowerCase(); 27 | } 28 | 29 | 30 | 31 | public ArrayList placeDotCom(int comSize) { // line 19 32 | ArrayList alphaCells = new ArrayList(); 33 | String [] alphacoords = new String [comSize]; // holds 'f6' type coords 34 | String temp = null; // temporary String for concat 35 | int [] coords = new int[comSize]; // current candidate coords 36 | int attempts = 0; // current attempts counter 37 | boolean success = false; // flag = found a good location ? 38 | int location = 0; // current starting location 39 | 40 | comCount++; // nth dot com to place 41 | int incr = 1; // set horizontal increment 42 | if ((comCount % 2) == 1) { // if odd dot com (place vertically) 43 | incr = gridLength; // set vertical increment 44 | } 45 | 46 | while ( !success & attempts++ < 200 ) { // main search loop (32) 47 | location = (int) (Math.random() * gridSize); // get random starting point 48 | //System.out.print(" try " + location); 49 | int x = 0; // nth position in dotcom to place 50 | success = true; // assume success 51 | while (success && x < comSize) { // look for adjacent unused spots 52 | if (grid[location] == 0) { // if not already used 53 | coords[x++] = location; // save location 54 | location += incr; // try 'next' adjacent 55 | if (location >= gridSize){ // out of bounds - 'bottom' 56 | success = false; // failure 57 | } 58 | if (x>0 & (location % gridLength == 0)) { // out of bounds - right edge 59 | success = false; // failure 60 | } 61 | } else { // found already used location 62 | // System.out.print(" used " + location); 63 | success = false; // failure 64 | } 65 | } 66 | } // end while 67 | 68 | int x = 0; // turn good location into alpha coords 69 | int row = 0; 70 | int column = 0; 71 | // System.out.println("\n"); 72 | while (x < comSize) { 73 | grid[coords[x]] = 1; // mark master grid pts. as 'used' 74 | row = (int) (coords[x] / gridLength); // get row value 75 | column = coords[x] % gridLength; // get numeric column value 76 | temp = String.valueOf(alphabet.charAt(column)); // convert to alpha 77 | 78 | alphaCells.add(temp.concat(Integer.toString(row))); 79 | x++; 80 | 81 | // System.out.print(" coord "+x+" = " + alphaCells.get(x-1)); 82 | 83 | } 84 | // System.out.println("\n"); 85 | 86 | return alphaCells; 87 | } 88 | } -------------------------------------------------------------------------------- /chap05/SimpleDotCom.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap05/SimpleDotCom.class -------------------------------------------------------------------------------- /chap05/SimpleDotCom.java: -------------------------------------------------------------------------------- 1 | package chap05; 2 | 3 | public class SimpleDotCom { 4 | int[] locationCells; 5 | int numOfHits = 0; 6 | 7 | public void setLocationCells(int[] locs) 8 | { 9 | locationCells = locs; 10 | } 11 | 12 | public String checkYourself(String stringGuess) { 13 | int guess = Integer.parseInt(stringGuess); 14 | String result = "miss"; 15 | for (int cell: locationCells) 16 | { 17 | if (guess == cell) { 18 | result = "hit"; 19 | numOfHits++; 20 | break; 21 | } 22 | } 23 | if (numOfHits == locationCells.length) 24 | { 25 | result = "kill"; 26 | } 27 | System.out.println(result); 28 | return result; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /chap05/SimpleDotComTester.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap05/SimpleDotComTester.class -------------------------------------------------------------------------------- /chap05/SimpleDotComTester.java: -------------------------------------------------------------------------------- 1 | package chap05; 2 | 3 | public class SimpleDotComTester { 4 | public static void main(String[] args) 5 | { 6 | SimpleDotCom dot = new SimpleDotCom(); 7 | int[] locations = {2, 3, 4}; 8 | dot.setLocationCells(locations); 9 | String userGuess = "2"; 10 | String result = dot.checkYourself(userGuess); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /chap06/DotCom.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap06/DotCom.class -------------------------------------------------------------------------------- /chap06/DotCom.java: -------------------------------------------------------------------------------- 1 | package chap06; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class DotCom { 6 | private ArrayList locationCells; 7 | 8 | public void setLocationCells(ArrayList loc) 9 | { 10 | locationCells = loc; 11 | } 12 | 13 | public String checkYourself(String userInput) 14 | { 15 | String result = "miss"; 16 | int index = locationCells.indexOf(userInput); 17 | if (index >= 0) { 18 | locationCells.remove(index); 19 | if (locationCells.isEmpty()) { 20 | result = "kill"; 21 | } 22 | else 23 | { 24 | result = "hit"; 25 | } 26 | } 27 | return result; 28 | } 29 | 30 | //TODO: all the following code was added and should have been included in the book 31 | private String name; 32 | public void setName(String string) { 33 | name = string; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /chap06/DotComBust.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap06/DotComBust.class -------------------------------------------------------------------------------- /chap06/DotComBust.java: -------------------------------------------------------------------------------- 1 | package chap06; 2 | import helpers.GameHelper; 3 | 4 | import java.util.*; 5 | 6 | public class DotComBust { 7 | private GameHelper helper = new GameHelper(); 8 | private ArrayList dotComsList = new ArrayList(); 9 | private int numOfGuesses = 0; 10 | 11 | private void setUpGame() { 12 | DotCom one = new DotCom(); 13 | one.setName("Pets.com"); 14 | DotCom two = new DotCom(); 15 | two.setName("eToys.com"); 16 | DotCom three = new DotCom(); 17 | three.setName("Go2.com"); 18 | dotComsList.add(one); 19 | dotComsList.add(two); 20 | dotComsList.add(three); 21 | 22 | System.out.println("Your goal is to sink three dot coms."); 23 | System.out.println("Pets.com, eToys.com, Go2.com"); 24 | System.out.println("Try to sink them all in the fewest number of guesses"); 25 | 26 | for (DotCom dotComSet : dotComsList) { 27 | ArrayList newLocation = helper.placeDotCom(3); 28 | dotComSet.setLocationCells(newLocation); 29 | } 30 | } 31 | 32 | private void startPlaying() { 33 | while (!dotComsList.isEmpty()) { 34 | String userGuess = helper.getUserInput("Enter a guess"); 35 | checkUserGuess(userGuess); 36 | } 37 | finishGame(); 38 | } 39 | 40 | private void checkUserGuess(String userGuess) 41 | { 42 | numOfGuesses++; 43 | String result = "miss"; 44 | 45 | for (DotCom dotComToTest : dotComsList) 46 | { 47 | result = dotComToTest.checkYourself(userGuess); 48 | if (result.equals("hit")) 49 | { 50 | break; 51 | } 52 | if (result.equals("kill")) 53 | { 54 | dotComsList.remove(dotComToTest); 55 | break; 56 | } 57 | } 58 | System.out.println(result); 59 | } 60 | 61 | private void finishGame() { 62 | System.out.println("All Dot Coms are dead! Your stock is now worthless"); 63 | if (numOfGuesses <= 18) { 64 | System.out.println("It only took you " + numOfGuesses + " guesses"); 65 | System.out.println("You got out before your options sank."); 66 | } 67 | else 68 | { 69 | System.out.println("Took you long enough. " + numOfGuesses + " guesses."); 70 | System.out.println("Fish are dancing with your options."); 71 | } 72 | } 73 | 74 | public static void main(String[] args) { 75 | DotComBust game = new DotComBust(); 76 | game.setUpGame(); 77 | game.startPlaying(); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /chap07/Boat.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap07/Boat.class -------------------------------------------------------------------------------- /chap07/Rowboat.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap07/Rowboat.class -------------------------------------------------------------------------------- /chap07/Sailboat.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap07/Sailboat.class -------------------------------------------------------------------------------- /chap07/TestBoat.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap07/TestBoat.class -------------------------------------------------------------------------------- /chap07/TestBoat.java: -------------------------------------------------------------------------------- 1 | package chap07; 2 | 3 | public class TestBoat 4 | { 5 | public static void main(String[] args) { 6 | Boat b1 = new Boat(); 7 | Sailboat b2 = new Sailboat(); 8 | Rowboat b3 = new Rowboat(); 9 | b2.setLength(32); 10 | b1.move(); 11 | b3.move(); 12 | b2.move(); 13 | } 14 | } 15 | 16 | class Boat { 17 | private int length; 18 | public void setLength(int len) { 19 | length = len; 20 | } 21 | public int getLength() { 22 | return length; 23 | } 24 | public void move() { 25 | System.out.print("drift "); 26 | } 27 | } 28 | 29 | class Rowboat extends Boat { 30 | public void rowTheBoat() { 31 | System.out.print("stroke natasha"); 32 | } 33 | } 34 | class Sailboat extends Boat { 35 | public void move() { 36 | System.out.print("hoist sail "); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /chap08/Acts.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap08/Acts.class -------------------------------------------------------------------------------- /chap08/Clowns.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap08/Clowns.class -------------------------------------------------------------------------------- /chap08/Nose.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap08/Nose.class -------------------------------------------------------------------------------- /chap08/Of76.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap08/Of76.class -------------------------------------------------------------------------------- /chap08/Of76.java: -------------------------------------------------------------------------------- 1 | package chap08; 2 | 3 | 4 | public class Of76 extends Clowns 5 | { 6 | public static void main(String[] args) { 7 | Nose[] i = new Nose[3]; 8 | i[0] = new Acts(); 9 | i[1] = new Clowns(); 10 | i[2] = new Of76(); 11 | for (int x = 0; x < 3; x++) { 12 | System.out.println(i[x].iMethod() + " " + i[x].getClass()); 13 | } 14 | } 15 | } 16 | 17 | interface Nose { public int iMethod(); } 18 | abstract class Picasso implements Nose { public int iMethod() { return 7; }} 19 | class Clowns extends Picasso { } 20 | class Acts extends Picasso { public int iMethod() { return 5; }} -------------------------------------------------------------------------------- /chap08/Picasso.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap08/Picasso.class -------------------------------------------------------------------------------- /chap09/RetentionBot.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap09/RetentionBot.class -------------------------------------------------------------------------------- /chap09/SimUnit.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap09/SimUnit.class -------------------------------------------------------------------------------- /chap09/TestLifeSupportSim.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap09/TestLifeSupportSim.class -------------------------------------------------------------------------------- /chap09/TestLifeSupportSim.java: -------------------------------------------------------------------------------- 1 | package chap09; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class TestLifeSupportSim 6 | { 7 | public static void main(String[] args) 8 | { 9 | ArrayList aList = new ArrayList(); 10 | V2Radiator v2 = new V2Radiator(aList); 11 | V3Radiator v3 = new V3Radiator(aList); 12 | for (int z = 0; z < 20; z++) 13 | { 14 | RetentionBot ret = new RetentionBot(aList); 15 | } 16 | 17 | //adding this to make sure the power is correct: 18 | int totalPower = 0; 19 | for(Object o : aList) 20 | { 21 | totalPower += ((SimUnit) o).powerUse(); 22 | } 23 | System.out.println("Total power: " + totalPower); 24 | } 25 | } 26 | 27 | class V2Radiator { 28 | V2Radiator(ArrayList list) { 29 | System.out.println("making a v2 radiator"); 30 | for(int x=0; x<5; x++) 31 | { 32 | list.add(new SimUnit("V2Radiator")); 33 | } 34 | } 35 | } 36 | class V3Radiator extends V2Radiator{ 37 | V3Radiator(ArrayList list) { 38 | super(list); 39 | for(int g=0; g<10; g++) 40 | { 41 | list.add(new SimUnit("V3Radiator")); 42 | } 43 | } 44 | } 45 | class RetentionBot { 46 | RetentionBot(ArrayList rlist) { 47 | rlist.add(new SimUnit("Retention")); 48 | } 49 | } 50 | class SimUnit { 51 | String botType; 52 | SimUnit(String type) { 53 | botType = type; 54 | } 55 | int powerUse() { 56 | if ("Retention".equals(botType)) 57 | { 58 | return 2; 59 | } 60 | else 61 | { 62 | return 4; 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /chap09/V2Radiator.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap09/V2Radiator.class -------------------------------------------------------------------------------- /chap09/V3Radiator.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap09/V3Radiator.class -------------------------------------------------------------------------------- /chap10/FullMoons.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap10/FullMoons.class -------------------------------------------------------------------------------- /chap10/FullMoons.java: -------------------------------------------------------------------------------- 1 | package chap10; 2 | 3 | import java.util.*; 4 | import static java.lang.System.out; 5 | 6 | public class FullMoons 7 | { 8 | static int DAY_IM = 1000 * 60 * 60 * 24; 9 | public static void main(String[] args) { 10 | Calendar c = Calendar.getInstance(); 11 | c.set(2004, 0, 7, 15, 40); 12 | long day1 = c.getTimeInMillis(); 13 | for (int x = 0; x < 60; x++) { 14 | day1 += (DAY_IM * 29.52); //TODO: added this last semi-colon 15 | c.setTimeInMillis(day1); 16 | out.println(String.format("full moon on %tc", c)); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /chap11/MiniMiniMusicApp.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap11/MiniMiniMusicApp.class -------------------------------------------------------------------------------- /chap11/MiniMiniMusicApp.java: -------------------------------------------------------------------------------- 1 | package chap11; 2 | import javax.sound.midi.*; 3 | 4 | 5 | public class MiniMiniMusicApp { // this is the first one 6 | 7 | public static void main(String[] args) { 8 | MiniMiniMusicApp mini = new MiniMiniMusicApp(); 9 | mini.play(); 10 | } 11 | 12 | public void play() { 13 | 14 | try { 15 | 16 | // make (and open) a sequencer, make a sequence and track 17 | 18 | Sequencer sequencer = MidiSystem.getSequencer(); 19 | sequencer.open(); 20 | 21 | Sequence seq = new Sequence(Sequence.PPQ, 4); 22 | Track track = seq.createTrack(); 23 | 24 | // now make two midi events (containing a midi message) 25 | MidiEvent event = null; 26 | 27 | // first make the message 28 | // then stick the message into a midi event 29 | // and add the event to the track 30 | 31 | ShortMessage a = new ShortMessage(); 32 | a.setMessage(144, 1, 44, 100); 33 | MidiEvent noteOn = new MidiEvent(a, 1); // <-- means at tick one, the above event happens 34 | track.add(noteOn); 35 | 36 | ShortMessage b = new ShortMessage(); 37 | b.setMessage(128, 1, 44, 100); 38 | MidiEvent noteOff = new MidiEvent(b, 16); // <-- means at tick one, the above event happens 39 | track.add(noteOff); 40 | 41 | // add the events to the track 42 | 43 | // add the sequence to the sequencer, set timing, and start 44 | sequencer.setSequence(seq); 45 | 46 | sequencer.start(); 47 | // new 48 | Thread.sleep(1000); 49 | sequencer.close(); 50 | System.exit(0); 51 | } catch (Exception ex) {ex.printStackTrace();} 52 | } // close play 53 | 54 | } // close class -------------------------------------------------------------------------------- /chap11/MiniMiniMusicCmdLine.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap11/MiniMiniMusicCmdLine.class -------------------------------------------------------------------------------- /chap11/MiniMiniMusicCmdLine.java: -------------------------------------------------------------------------------- 1 | package chap11; 2 | import javax.sound.midi.*; 3 | 4 | 5 | public class MiniMiniMusicCmdLine { // this is the first one 6 | 7 | public static void main(String[] args) { 8 | MiniMiniMusicCmdLine mini = new MiniMiniMusicCmdLine(); 9 | if (args.length < 2) { 10 | System.out.println("Don't forget the instrument and note args"); 11 | } else { 12 | int instrument = Integer.parseInt(args[0]); 13 | int note = Integer.parseInt(args[1]); 14 | mini.play(instrument, note); 15 | 16 | } 17 | } 18 | 19 | public void play(int instrument, int note) { 20 | 21 | try { 22 | 23 | Sequencer player = MidiSystem.getSequencer(); 24 | player.open(); 25 | 26 | Sequence seq = new Sequence(Sequence.PPQ, 4); 27 | Track track = seq.createTrack(); 28 | 29 | MidiEvent event = null; 30 | 31 | ShortMessage first = new ShortMessage(); 32 | first.setMessage(192, 1, instrument, 0); 33 | MidiEvent changeInstrument = new MidiEvent(first, 1); 34 | track.add(changeInstrument); 35 | 36 | 37 | ShortMessage a = new ShortMessage(); 38 | a.setMessage(144, 1, note, 100); 39 | MidiEvent noteOn = new MidiEvent(a, 1); 40 | track.add(noteOn); 41 | 42 | ShortMessage b = new ShortMessage(); 43 | b.setMessage(128, 1, note, 100); 44 | MidiEvent noteOff = new MidiEvent(b, 16); 45 | track.add(noteOff); 46 | player.setSequence(seq); 47 | player.start(); 48 | // new 49 | Thread.sleep(5000); 50 | player.close(); 51 | System.exit(0); 52 | 53 | } catch (Exception ex) {ex.printStackTrace();} 54 | } // close play 55 | 56 | } // close class -------------------------------------------------------------------------------- /chap12/Animate$MyDrawP.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap12/Animate$MyDrawP.class -------------------------------------------------------------------------------- /chap12/Animate.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap12/Animate.class -------------------------------------------------------------------------------- /chap12/Animate.java: -------------------------------------------------------------------------------- 1 | package chap12; 2 | import javax.swing.*; import java.awt.*; public class Animate { int x = 1; int y = 1; public static void main (String[] args) { Animate gui = new Animate (); gui.go(); } public void go() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); MyDrawP drawP = new MyDrawP(); frame.getContentPane().add(drawP); frame.setSize(500,270); frame.setVisible(true); for (int i = 0; i < 124; i++,x++,y++ ) { x++; drawP.repaint(); try { Thread.sleep(50); } catch(Exception ex) { } } } class MyDrawP extends JPanel { public void paintComponent(Graphics g ) { g.setColor(Color.white); g.fillRect(0,0,500,250); g.setColor(Color.blue); g.fillRect(x,y,500-x*2,250-y*2); } } 3 | } -------------------------------------------------------------------------------- /chap12/MiniMusicPlayer3$MyDrawPanel.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap12/MiniMusicPlayer3$MyDrawPanel.class -------------------------------------------------------------------------------- /chap12/MiniMusicPlayer3.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap12/MiniMusicPlayer3.class -------------------------------------------------------------------------------- /chap12/MiniMusicPlayer3.java: -------------------------------------------------------------------------------- 1 | package chap12; 2 | import javax.sound.midi.*; 3 | import java.io.*; 4 | import javax.swing.*; 5 | import java.awt.*; 6 | 7 | // this one plays random music with it, but only because there is a listener. 8 | 9 | public class MiniMusicPlayer3 { 10 | 11 | static JFrame f = new JFrame("My First Music Video"); 12 | static MyDrawPanel ml; 13 | 14 | public static void main(String[] args) { 15 | MiniMusicPlayer3 mini = new MiniMusicPlayer3(); 16 | mini.go(); 17 | } 18 | 19 | 20 | public void setUpGui() { 21 | ml = new MyDrawPanel(); 22 | f.setContentPane(ml); 23 | f.setBounds(30,30, 300,300); 24 | f.setVisible(true); 25 | } 26 | 27 | 28 | public void go() { 29 | setUpGui(); 30 | 31 | try { 32 | 33 | // make (and open) a sequencer, make a sequence and track 34 | 35 | Sequencer sequencer = MidiSystem.getSequencer(); 36 | sequencer.open(); 37 | 38 | sequencer.addControllerEventListener(ml, new int[] {127}); 39 | Sequence seq = new Sequence(Sequence.PPQ, 4); 40 | Track track = seq.createTrack(); 41 | 42 | // now make two midi events (containing a midi message) 43 | 44 | int r = 0; 45 | for (int i = 0; i < 60; i+= 4) { 46 | 47 | r = (int) ((Math.random() * 50) + 1); 48 | 49 | track.add(makeEvent(144,1,r,100,i)); 50 | 51 | track.add(makeEvent(176,1,127,0,i)); 52 | 53 | track.add(makeEvent(128,1,r,100,i + 2)); 54 | } // end loop 55 | 56 | // add the events to the track 57 | // add the sequence to the sequencer, set timing, and start 58 | 59 | sequencer.setSequence(seq); 60 | 61 | sequencer.start(); 62 | sequencer.setTempoInBPM(120); 63 | } catch (Exception ex) {ex.printStackTrace();} 64 | } // close go 65 | 66 | 67 | public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) { 68 | MidiEvent event = null; 69 | try { 70 | ShortMessage a = new ShortMessage(); 71 | a.setMessage(comd, chan, one, two); 72 | event = new MidiEvent(a, tick); 73 | 74 | }catch(Exception e) { } 75 | return event; 76 | } 77 | 78 | 79 | 80 | class MyDrawPanel extends JPanel implements ControllerEventListener { 81 | 82 | // only if we got an event do we want to paint 83 | boolean msg = false; 84 | 85 | public void controlChange(ShortMessage event) { 86 | msg = true; 87 | repaint(); 88 | } 89 | 90 | public void paintComponent(Graphics g) { 91 | if (msg) { 92 | 93 | Graphics2D g2 = (Graphics2D) g; 94 | 95 | int r = (int) (Math.random() * 250); 96 | int gr = (int) (Math.random() * 250); 97 | int b = (int) (Math.random() * 250); 98 | 99 | g.setColor(new Color(r,gr,b)); 100 | 101 | int ht = (int) ((Math.random() * 120) + 10); 102 | int width = (int) ((Math.random() * 120) + 10); 103 | 104 | int x = (int) ((Math.random() * 40) + 10); 105 | int y = (int) ((Math.random() * 40) + 10); 106 | 107 | g.fillRect(x,y,ht, width); 108 | msg = false; 109 | 110 | } // close if 111 | } // close method 112 | } // close inner class 113 | 114 | } // close class -------------------------------------------------------------------------------- /chap12/MyDrawPanel.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap12/MyDrawPanel.class -------------------------------------------------------------------------------- /chap12/SimpleAnimation$MyDrawPanel.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap12/SimpleAnimation$MyDrawPanel.class -------------------------------------------------------------------------------- /chap12/SimpleAnimation.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap12/SimpleAnimation.class -------------------------------------------------------------------------------- /chap12/SimpleAnimation.java: -------------------------------------------------------------------------------- 1 | package chap12; 2 | import javax.swing.*; import java.awt.*; public class SimpleAnimation { int x = 70; int y = 70; public static void main (String[] args) { SimpleAnimation gui = new SimpleAnimation (); gui.go(); } public void go() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); MyDrawPanel drawPanel = new MyDrawPanel(); frame.getContentPane().add(drawPanel); frame.setSize(300,300); frame.setVisible(true); for (int i = 0; i < 130; i++) { x++; y++; drawPanel.repaint(); try { Thread.sleep(50); } catch(Exception ex) { } } }// close go() method class MyDrawPanel extends JPanel { public void paintComponent(Graphics g) { 3 | g.setColor(Color.white); g.fillRect(0,0,this.getWidth(), this.getHeight()); 4 | g.setColor(Color.green); g.fillOval(x,y,40,40); } } // close inner class } // close outer class 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /chap12/TwoButtons$ColorButtonListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap12/TwoButtons$ColorButtonListener.class -------------------------------------------------------------------------------- /chap12/TwoButtons$LabelButtonListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap12/TwoButtons$LabelButtonListener.class -------------------------------------------------------------------------------- /chap12/TwoButtons.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap12/TwoButtons.class -------------------------------------------------------------------------------- /chap12/TwoButtons.java: -------------------------------------------------------------------------------- 1 | package chap12; 2 | import javax.swing.*; 3 | import java.awt.*; 4 | import java.awt.event.*; 5 | 6 | 7 | public class TwoButtons { 8 | 9 | JFrame frame; 10 | JLabel label; 11 | 12 | public static void main (String[] args) { 13 | TwoButtons gui = new TwoButtons(); 14 | gui.go(); 15 | } 16 | 17 | public void go() { 18 | frame = new JFrame(); 19 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 20 | 21 | JButton labelButton = new JButton("Change Label"); 22 | labelButton.addActionListener(new LabelButtonListener()); 23 | 24 | JButton colorButton = new JButton("Change Circle"); 25 | colorButton.addActionListener(new ColorButtonListener()); 26 | 27 | label = new JLabel("I'm a label"); 28 | MyDrawPanel drawPanel = new MyDrawPanel(); 29 | 30 | frame.getContentPane().add(BorderLayout.SOUTH, colorButton); 31 | frame.getContentPane().add(BorderLayout.CENTER, drawPanel); 32 | frame.getContentPane().add(BorderLayout.EAST, labelButton); 33 | frame.getContentPane().add(BorderLayout.WEST, label); 34 | 35 | frame.setSize(420,300); 36 | frame.setVisible(true); 37 | } 38 | 39 | class LabelButtonListener implements ActionListener { 40 | public void actionPerformed(ActionEvent event) { 41 | label.setText("Ouch!"); 42 | } 43 | } // close inner class 44 | 45 | class ColorButtonListener implements ActionListener { 46 | public void actionPerformed(ActionEvent event) { 47 | frame.repaint(); 48 | } 49 | } // close inner class 50 | 51 | } 52 | 53 | class MyDrawPanel extends JPanel { 54 | 55 | public void paintComponent(Graphics g) { 56 | 57 | g.fillRect(0,0,this.getWidth(), this.getHeight()); 58 | 59 | // make random colors to fill with 60 | int red = (int) (Math.random() * 255); 61 | int green = (int) (Math.random() * 255); 62 | int blue = (int) (Math.random() * 255); 63 | 64 | Color randomColor = new Color(red, green, blue); 65 | g.setColor(randomColor); 66 | g.fillOval(70,70,100,100); 67 | } 68 | 69 | } 70 | 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /chap13/BeatBox$MyDownTempoListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap13/BeatBox$MyDownTempoListener.class -------------------------------------------------------------------------------- /chap13/BeatBox$MyStartListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap13/BeatBox$MyStartListener.class -------------------------------------------------------------------------------- /chap13/BeatBox$MyStopListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap13/BeatBox$MyStopListener.class -------------------------------------------------------------------------------- /chap13/BeatBox$MyUpTempoListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap13/BeatBox$MyUpTempoListener.class -------------------------------------------------------------------------------- /chap13/BeatBox.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap13/BeatBox.class -------------------------------------------------------------------------------- /chap13/BeatBox.java: -------------------------------------------------------------------------------- 1 | package chap13; 2 | // chapter 13 3 | 4 | import java.awt.*; 5 | import javax.swing.*; 6 | import javax.sound.midi.*; 7 | import java.util.*; 8 | import java.awt.event.*; 9 | 10 | public class BeatBox { 11 | 12 | JPanel mainPanel; 13 | ArrayList checkboxList; 14 | Sequencer sequencer; 15 | Sequence sequence; 16 | Track track; 17 | JFrame theFrame; 18 | 19 | String[] instrumentNames = {"Bass Drum", "Closed Hi-Hat", 20 | "Open Hi-Hat","Acoustic Snare", "Crash Cymbal", "Hand Clap", 21 | "High Tom", "Hi Bongo", "Maracas", "Whistle", "Low Conga", 22 | "Cowbell", "Vibraslap", "Low-mid Tom", "High Agogo", 23 | "Open Hi Conga"}; 24 | int[] instruments = {35,42,46,38,49,39,50,60,70,72,64,56,58,47,67,63}; 25 | 26 | 27 | public static void main (String[] args) { 28 | new BeatBox().buildGUI(); 29 | } 30 | 31 | public void buildGUI() { 32 | theFrame = new JFrame("Cyber BeatBox"); 33 | theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 34 | BorderLayout layout = new BorderLayout(); 35 | JPanel background = new JPanel(layout); 36 | background.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); 37 | 38 | checkboxList = new ArrayList(); 39 | Box buttonBox = new Box(BoxLayout.Y_AXIS); 40 | 41 | JButton start = new JButton("Start"); 42 | start.addActionListener(new MyStartListener()); 43 | buttonBox.add(start); 44 | 45 | JButton stop = new JButton("Stop"); 46 | stop.addActionListener(new MyStopListener()); 47 | buttonBox.add(stop); 48 | 49 | JButton upTempo = new JButton("Tempo Up"); 50 | upTempo.addActionListener(new MyUpTempoListener()); 51 | buttonBox.add(upTempo); 52 | 53 | JButton downTempo = new JButton("Tempo Down"); 54 | downTempo.addActionListener(new MyDownTempoListener()); 55 | buttonBox.add(downTempo); 56 | 57 | Box nameBox = new Box(BoxLayout.Y_AXIS); 58 | for (int i = 0; i < 16; i++) { 59 | nameBox.add(new Label(instrumentNames[i])); 60 | } 61 | 62 | background.add(BorderLayout.EAST, buttonBox); 63 | background.add(BorderLayout.WEST, nameBox); 64 | 65 | theFrame.getContentPane().add(background); 66 | 67 | GridLayout grid = new GridLayout(16,16); 68 | grid.setVgap(1); 69 | grid.setHgap(2); 70 | mainPanel = new JPanel(grid); 71 | background.add(BorderLayout.CENTER, mainPanel); 72 | 73 | for (int i = 0; i < 256; i++) { 74 | JCheckBox c = new JCheckBox(); 75 | c.setSelected(false); 76 | checkboxList.add(c); 77 | mainPanel.add(c); 78 | } // end loop 79 | 80 | setUpMidi(); 81 | 82 | theFrame.setBounds(50,50,300,300); 83 | theFrame.pack(); 84 | theFrame.setVisible(true); 85 | } // close method 86 | 87 | 88 | public void setUpMidi() { 89 | try { 90 | sequencer = MidiSystem.getSequencer(); 91 | sequencer.open(); 92 | sequence = new Sequence(Sequence.PPQ,4); 93 | track = sequence.createTrack(); 94 | sequencer.setTempoInBPM(120); 95 | 96 | } catch(Exception e) {e.printStackTrace();} 97 | } // close method 98 | 99 | public void buildTrackAndStart() { 100 | int[] trackList = null; 101 | 102 | sequence.deleteTrack(track); 103 | track = sequence.createTrack(); 104 | 105 | for (int i = 0; i < 16; i++) { 106 | trackList = new int[16]; 107 | 108 | int key = instruments[i]; 109 | 110 | for (int j = 0; j < 16; j++ ) { 111 | JCheckBox jc = (JCheckBox) checkboxList.get(j + (16*i)); 112 | if ( jc.isSelected()) { 113 | trackList[j] = key; 114 | } else { 115 | trackList[j] = 0; 116 | } 117 | } // close inner loop 118 | 119 | makeTracks(trackList); 120 | track.add(makeEvent(176,1,127,0,16)); 121 | } // close outer 122 | 123 | track.add(makeEvent(192,9,1,0,15)); 124 | try { 125 | sequencer.setSequence(sequence); 126 | sequencer.setLoopCount(sequencer.LOOP_CONTINUOUSLY); 127 | sequencer.start(); 128 | sequencer.setTempoInBPM(120); 129 | } catch(Exception e) {e.printStackTrace();} 130 | } // close buildTrackAndStart method 131 | 132 | 133 | public class MyStartListener implements ActionListener { 134 | public void actionPerformed(ActionEvent a) { 135 | buildTrackAndStart(); 136 | } 137 | } // close inner class 138 | 139 | public class MyStopListener implements ActionListener { 140 | public void actionPerformed(ActionEvent a) { 141 | sequencer.stop(); 142 | } 143 | } // close inner class 144 | 145 | public class MyUpTempoListener implements ActionListener { 146 | public void actionPerformed(ActionEvent a) { 147 | float tempoFactor = sequencer.getTempoFactor(); 148 | sequencer.setTempoFactor((float)(tempoFactor * 1.03)); 149 | } 150 | } // close inner class 151 | 152 | public class MyDownTempoListener implements ActionListener { 153 | public void actionPerformed(ActionEvent a) { 154 | float tempoFactor = sequencer.getTempoFactor(); 155 | sequencer.setTempoFactor((float)(tempoFactor * .97)); 156 | } 157 | } // close inner class 158 | 159 | public void makeTracks(int[] list) { 160 | 161 | for (int i = 0; i < 16; i++) { 162 | int key = list[i]; 163 | 164 | if (key != 0) { 165 | track.add(makeEvent(144,9,key, 100, i)); 166 | track.add(makeEvent(128,9,key, 100, i+1)); 167 | } 168 | } 169 | } 170 | 171 | public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) { 172 | MidiEvent event = null; 173 | try { 174 | ShortMessage a = new ShortMessage(); 175 | a.setMessage(comd, chan, one, two); 176 | event = new MidiEvent(a, tick); 177 | 178 | } catch(Exception e) {e.printStackTrace(); } 179 | return event; 180 | } 181 | 182 | } // close class 183 | 184 | 185 | 186 | 187 | 188 | -------------------------------------------------------------------------------- /chap14/BeatBoxSaveOnly$MyDownTempoListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/BeatBoxSaveOnly$MyDownTempoListener.class -------------------------------------------------------------------------------- /chap14/BeatBoxSaveOnly$MyReadInListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/BeatBoxSaveOnly$MyReadInListener.class -------------------------------------------------------------------------------- /chap14/BeatBoxSaveOnly$MySendListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/BeatBoxSaveOnly$MySendListener.class -------------------------------------------------------------------------------- /chap14/BeatBoxSaveOnly$MyStartListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/BeatBoxSaveOnly$MyStartListener.class -------------------------------------------------------------------------------- /chap14/BeatBoxSaveOnly$MyStopListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/BeatBoxSaveOnly$MyStopListener.class -------------------------------------------------------------------------------- /chap14/BeatBoxSaveOnly$MyUpTempoListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/BeatBoxSaveOnly$MyUpTempoListener.class -------------------------------------------------------------------------------- /chap14/BeatBoxSaveOnly.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/BeatBoxSaveOnly.class -------------------------------------------------------------------------------- /chap14/BeatBoxSaveOnly.java: -------------------------------------------------------------------------------- 1 | package chap14; 2 | // chapter 14 3 | 4 | import java.awt.*; 5 | import javax.swing.*; 6 | import java.io.*; 7 | import javax.sound.midi.*; 8 | import java.util.*; 9 | import java.awt.event.*; 10 | 11 | 12 | public class BeatBoxSaveOnly { // implements MetaEventListener 13 | 14 | JPanel mainPanel; 15 | ArrayList checkboxList; 16 | // int bpm = 120; 17 | Sequencer sequencer; 18 | Sequence sequence; 19 | Sequence mySequence = null; 20 | Track track; 21 | JFrame theFrame; 22 | 23 | String[] instrumentNames = {"Bass Drum", "Closed Hi-Hat", 24 | "Open Hi-Hat","Acoustic Snare", "Crash Cymbal", "Hand Clap", 25 | "High Tom", "Hi Bongo", "Maracas", "Whistle", "Low Conga", 26 | "Cowbell", "Vibraslap", "Low-mid Tom", "High Agogo", 27 | "Open Hi Conga"}; 28 | int[] instruments = {35,42,46,38,49,39,50,60,70,72,64,56,58,47,67,63}; 29 | 30 | 31 | public static void main (String[] args) { 32 | new BeatBoxSaveOnly().buildGUI(); 33 | } 34 | 35 | public void buildGUI() { 36 | theFrame = new JFrame("Cyber BeatBox"); 37 | theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 38 | BorderLayout layout = new BorderLayout(); 39 | JPanel background = new JPanel(layout); 40 | background.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); 41 | 42 | checkboxList = new ArrayList(); 43 | Box buttonBox = new Box(BoxLayout.Y_AXIS); 44 | 45 | JButton start = new JButton("Start"); 46 | start.addActionListener(new MyStartListener()); 47 | buttonBox.add(start); 48 | 49 | 50 | JButton stop = new JButton("Stop"); 51 | stop.addActionListener(new MyStopListener()); 52 | buttonBox.add(stop); 53 | 54 | JButton upTempo = new JButton("Tempo Up"); 55 | upTempo.addActionListener(new MyUpTempoListener()); 56 | buttonBox.add(upTempo); 57 | 58 | JButton downTempo = new JButton("Tempo Down"); 59 | downTempo.addActionListener(new MyDownTempoListener()); 60 | buttonBox.add(downTempo); 61 | 62 | JButton saveIt = new JButton("Serialize It"); // new button 63 | saveIt.addActionListener(new MySendListener()); 64 | buttonBox.add(saveIt); 65 | 66 | JButton restore = new JButton("Restore"); // new button 67 | restore.addActionListener(new MyReadInListener()); 68 | buttonBox.add(restore); 69 | 70 | Box nameBox = new Box(BoxLayout.Y_AXIS); 71 | for (int i = 0; i < 16; i++) { 72 | nameBox.add(new Label(instrumentNames[i])); 73 | } 74 | 75 | background.add(BorderLayout.EAST, buttonBox); 76 | background.add(BorderLayout.WEST, nameBox); 77 | 78 | theFrame.getContentPane().add(background); 79 | 80 | GridLayout grid = new GridLayout(16,16); 81 | grid.setVgap(1); 82 | grid.setHgap(2); 83 | mainPanel = new JPanel(grid); 84 | background.add(BorderLayout.CENTER, mainPanel); 85 | 86 | 87 | for (int i = 0; i < 256; i++) { 88 | JCheckBox c = new JCheckBox(); 89 | c.setSelected(false); 90 | checkboxList.add(c); 91 | mainPanel.add(c); 92 | } // end loop 93 | 94 | setUpMidi(); 95 | 96 | theFrame.setBounds(50,50,300,300); 97 | theFrame.pack(); 98 | theFrame.setVisible(true); 99 | } // close method 100 | 101 | 102 | public void setUpMidi() { 103 | try { 104 | sequencer = MidiSystem.getSequencer(); 105 | sequencer.open(); 106 | // sequencer.addMetaEventListener(this); 107 | sequence = new Sequence(Sequence.PPQ,4); 108 | track = sequence.createTrack(); 109 | sequencer.setTempoInBPM(120); 110 | 111 | } catch(Exception e) {e.printStackTrace();} 112 | } // close method 113 | /* 114 | public class MyCheckBoxListener implements ItemListener { 115 | public void itemStateChanged(ItemEvent ev) { 116 | // might add real-time removal or addition, probably not because of timing 117 | } 118 | } // close inner class 119 | */ 120 | 121 | public void buildTrackAndStart() { 122 | // this will hold the instruments for each vertical column, 123 | // in other words, each tick (may have multiple instruments) 124 | int[] trackList = null; 125 | 126 | sequence.deleteTrack(track); 127 | track = sequence.createTrack(); 128 | 129 | 130 | for (int i = 0; i < 16; i++) { 131 | trackList = new int[16]; 132 | 133 | int key = instruments[i]; 134 | 135 | for (int j = 0; j < 16; j++ ) { 136 | JCheckBox jc = (JCheckBox) checkboxList.get(j + (16*i)); 137 | 138 | if ( jc.isSelected()) { 139 | trackList[j] = key; 140 | } else { 141 | trackList[j] = 0; 142 | } 143 | } // close inner 144 | 145 | makeTracks(trackList); 146 | } // close outer 147 | 148 | track.add(makeEvent(192,9,1,0,15)); // - so we always go to full 16 beats 149 | 150 | 151 | 152 | try { 153 | 154 | sequencer.setSequence(sequence); 155 | sequencer.setLoopCount(sequencer.LOOP_CONTINUOUSLY); 156 | sequencer.start(); 157 | sequencer.setTempoInBPM(120); 158 | } catch(Exception e) {e.printStackTrace();} 159 | 160 | } // close method 161 | 162 | //============================================================== inner class listeners 163 | 164 | public class MyStartListener implements ActionListener { 165 | public void actionPerformed(ActionEvent a) { 166 | buildTrackAndStart(); 167 | } 168 | } 169 | 170 | public class MyStopListener implements ActionListener { 171 | public void actionPerformed(ActionEvent a) { 172 | sequencer.stop(); 173 | } 174 | } 175 | 176 | public class MyUpTempoListener implements ActionListener { 177 | public void actionPerformed(ActionEvent a) { 178 | float tempoFactor = sequencer.getTempoFactor(); 179 | sequencer.setTempoFactor((float)(tempoFactor * 1.03)); 180 | } 181 | } 182 | 183 | public class MyDownTempoListener implements ActionListener { 184 | public void actionPerformed(ActionEvent a) { 185 | float tempoFactor = sequencer.getTempoFactor(); 186 | sequencer.setTempoFactor((float)(tempoFactor * .97)); 187 | } 188 | } 189 | 190 | public class MySendListener implements ActionListener { // new - save 191 | public void actionPerformed(ActionEvent a) { 192 | // make an arraylist of just the STATE of the checkboxes 193 | boolean[] checkboxState = new boolean[256]; 194 | 195 | for (int i = 0; i < 256; i++) { 196 | JCheckBox check = (JCheckBox) checkboxList.get(i); 197 | if (check.isSelected()) { 198 | checkboxState[i] = true; 199 | } 200 | } 201 | 202 | try { 203 | FileOutputStream fileStream = new FileOutputStream( 204 | new File("Checkbox.ser")); 205 | ObjectOutputStream os = new ObjectOutputStream(fileStream); 206 | os.writeObject(checkboxState); 207 | } catch(Exception ex) { 208 | ex.printStackTrace(); 209 | } 210 | 211 | } // close method 212 | } // close inner class 213 | 214 | 215 | 216 | public class MyReadInListener implements ActionListener { // new - restore 217 | public void actionPerformed(ActionEvent a) { 218 | // read in the thing 219 | 220 | boolean[] checkboxState = null; 221 | try { 222 | FileInputStream fileIn = new FileInputStream( 223 | new File("Checkbox.ser")); 224 | ObjectInputStream is = new ObjectInputStream(fileIn); 225 | checkboxState = (boolean[]) is.readObject(); 226 | 227 | } catch(Exception ex) {ex.printStackTrace();} 228 | 229 | // now reset the sequence to be this 230 | for (int i = 0; i < 256; i++) { 231 | JCheckBox check = (JCheckBox) checkboxList.get(i); 232 | if (checkboxState[i]) { 233 | check.setSelected(true); 234 | } else { 235 | check.setSelected(false); 236 | } 237 | } 238 | 239 | 240 | 241 | // now stop sequence and restart 242 | sequencer.stop(); 243 | buildTrackAndStart(); 244 | } // close method 245 | } // close inner class 246 | 247 | 248 | //============================================================== 249 | 250 | public void makeTracks(int[] list) { 251 | 252 | for (int i = 0; i < 16; i++) { 253 | int key = list[i]; 254 | 255 | if (key != 0) { 256 | track.add(makeEvent(144,9,key, 100, i)); 257 | track.add(makeEvent(128,9,key, 100, i + 1)); 258 | } 259 | } 260 | } 261 | 262 | 263 | 264 | public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) { 265 | MidiEvent event = null; 266 | try { 267 | ShortMessage a = new ShortMessage(); 268 | a.setMessage(comd, chan, one, two); 269 | event = new MidiEvent(a, tick); 270 | 271 | }catch(Exception e) { } 272 | return event; 273 | } 274 | 275 | /* 276 | public void meta(MetaMessage message) { 277 | if (message.getType() == 47) { 278 | sequencer.start(); 279 | sequencer.setTempoInBPM(bpm); 280 | } 281 | } 282 | */ 283 | 284 | 285 | } // close class 286 | 287 | 288 | 289 | 290 | 291 | -------------------------------------------------------------------------------- /chap14/DungeonGame.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/DungeonGame.class -------------------------------------------------------------------------------- /chap14/DungeonTest.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/DungeonTest.class -------------------------------------------------------------------------------- /chap14/DungeonTest.java: -------------------------------------------------------------------------------- 1 | package chap14; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileOutputStream; 5 | import java.io.ObjectInputStream; 6 | import java.io.ObjectOutputStream; 7 | import java.io.Serializable; 8 | 9 | public class DungeonTest 10 | { 11 | public static void main(String[] args) { 12 | DungeonGame d = new DungeonGame(); 13 | System.out.println(d.getX() + d.getY() + d.getZ()); 14 | try { 15 | FileOutputStream fos = new FileOutputStream("dg.ser"); 16 | ObjectOutputStream oos = new ObjectOutputStream(fos); 17 | oos.writeObject(d); 18 | oos.close(); 19 | FileInputStream fis = new FileInputStream("dg.ser"); 20 | ObjectInputStream ois = new ObjectInputStream(fis); 21 | d = (DungeonGame) ois.readObject(); 22 | ois.close(); 23 | } 24 | catch (Exception e) 25 | { 26 | e.printStackTrace(); 27 | } 28 | System.out.println(d.getX() + d.getY() + d.getZ()); 29 | } 30 | } 31 | 32 | 33 | class DungeonGame implements Serializable { 34 | public int x = 3; 35 | transient long y= 4; 36 | private short z = 5; 37 | int getX() { 38 | return x; 39 | } 40 | long getY() { 41 | return y; 42 | } 43 | short getZ() { 44 | return z; 45 | } 46 | } -------------------------------------------------------------------------------- /chap14/GameCharacter.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/GameCharacter.class -------------------------------------------------------------------------------- /chap14/GameCharacter.java: -------------------------------------------------------------------------------- 1 | package chap14; 2 | 3 | import java.io.Serializable; 4 | 5 | public class GameCharacter implements Serializable 6 | { 7 | int power; 8 | String type; 9 | String[] weapons; 10 | 11 | public GameCharacter(int p, String t, String[] w) 12 | { 13 | power = p; 14 | type = t; 15 | weapons = w; 16 | } 17 | 18 | public int getPower() { 19 | return power; 20 | } 21 | 22 | public String getType() { 23 | return type; 24 | } 25 | 26 | public String getWeapons() { 27 | String weaponList = ""; 28 | for (int i = 0; i < weapons.length; i++) 29 | { 30 | weaponList += weapons[i] + " "; 31 | } 32 | return weaponList; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /chap14/GameSaverTest.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/GameSaverTest.class -------------------------------------------------------------------------------- /chap14/GameSaverTest.java: -------------------------------------------------------------------------------- 1 | package chap14; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.io.ObjectInputStream; 7 | import java.io.ObjectOutputStream; 8 | import java.io.OutputStream; 9 | 10 | public class GameSaverTest 11 | { 12 | public static void main (String[] args) { 13 | GameCharacter one = new GameCharacter(50, "Elf", new String[] {"bow", "sword", "dust"}); 14 | GameCharacter two = new GameCharacter(200, "Troll", new String[] {"bare hands", "big axe"}); 15 | GameCharacter three = new GameCharacter(120, "Magician", new String[] {"spells", "invisibility"}); 16 | 17 | try { 18 | ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("Game.ser")); 19 | os.writeObject(one); 20 | os.writeObject(two); 21 | os.writeObject(three); 22 | os.close(); 23 | } 24 | catch (IOException ex) { 25 | ex.printStackTrace(); 26 | } 27 | 28 | one = null; 29 | two = null; 30 | three = null; 31 | 32 | try { 33 | ObjectInputStream is = new ObjectInputStream(new FileInputStream("Game.ser")); 34 | GameCharacter oneRestore = (GameCharacter) is.readObject(); 35 | GameCharacter twoRestore = (GameCharacter) is.readObject(); 36 | GameCharacter threeRestore = (GameCharacter) is.readObject(); 37 | 38 | System.out.println("One's type: " + oneRestore.getType()); 39 | System.out.println("Two's type: " + twoRestore.getType()); 40 | System.out.println("Three's type: " + threeRestore.getType()); 41 | } 42 | catch (Exception ex) { 43 | ex.printStackTrace(); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /chap14/QuizCard.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/QuizCard.class -------------------------------------------------------------------------------- /chap14/QuizCard.java: -------------------------------------------------------------------------------- 1 | package chap14; 2 | import java.io.*; 3 | 4 | public class QuizCard implements Serializable { 5 | 6 | private String uniqueID; 7 | private String category; 8 | private String question; 9 | private String answer; 10 | private String hint; 11 | 12 | public QuizCard(String q, String a) { 13 | question = q; 14 | answer = a; 15 | } 16 | 17 | 18 | public void setUniqueID(String id) { 19 | uniqueID = id; 20 | } 21 | 22 | public String getUniqueID() { 23 | return uniqueID; 24 | } 25 | 26 | public void setCategory(String c) { 27 | category = c; 28 | } 29 | 30 | public String getCategory() { 31 | return category; 32 | } 33 | 34 | public void setQuestion(String q) { 35 | question = q; 36 | } 37 | 38 | public String getQuestion() { 39 | return question; 40 | } 41 | 42 | public void setAnswer(String a) { 43 | answer = a; 44 | } 45 | 46 | public String getAnswer() { 47 | return answer; 48 | } 49 | 50 | public void setHint(String h) { 51 | hint = h; 52 | } 53 | 54 | public String getHint() { 55 | return hint; 56 | } 57 | 58 | } 59 | 60 | -------------------------------------------------------------------------------- /chap14/QuizCardBuilder$NewMenuListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/QuizCardBuilder$NewMenuListener.class -------------------------------------------------------------------------------- /chap14/QuizCardBuilder$NextCardListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/QuizCardBuilder$NextCardListener.class -------------------------------------------------------------------------------- /chap14/QuizCardBuilder$SaveMenuListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/QuizCardBuilder$SaveMenuListener.class -------------------------------------------------------------------------------- /chap14/QuizCardBuilder.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/QuizCardBuilder.class -------------------------------------------------------------------------------- /chap14/QuizCardBuilder.java: -------------------------------------------------------------------------------- 1 | package chap14; 2 | import java.util.*; 3 | import java.awt.event.*; 4 | import javax.swing.*; 5 | import java.awt.*; 6 | import java.io.*; 7 | 8 | public class QuizCardBuilder { 9 | 10 | private JTextArea question; 11 | private JTextArea answer; 12 | private ArrayList cardList; 13 | private JFrame frame; 14 | 15 | // additional, bonus method not found in any book! 16 | 17 | public static void main (String[] args) { 18 | QuizCardBuilder builder = new QuizCardBuilder(); 19 | builder.go(); 20 | } 21 | 22 | public void go() { 23 | // build gui 24 | frame = new JFrame("Quiz Card Builder"); 25 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // title bar 26 | JPanel mainPanel = new JPanel(); 27 | Font bigFont = new Font("sanserif", Font.BOLD, 24); 28 | question = new JTextArea(6,20); 29 | question.setLineWrap(true); 30 | question.setWrapStyleWord(true); 31 | question.setFont(bigFont); 32 | 33 | JScrollPane qScroller = new JScrollPane(question); 34 | qScroller.setVerticalScrollBarPolicy( 35 | ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 36 | qScroller.setHorizontalScrollBarPolicy( 37 | ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); 38 | 39 | answer = new JTextArea(6,20); 40 | answer.setLineWrap(true); 41 | answer.setWrapStyleWord(true); 42 | answer.setFont(bigFont); 43 | 44 | JScrollPane aScroller = new JScrollPane(answer); 45 | aScroller.setVerticalScrollBarPolicy( 46 | ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 47 | aScroller.setHorizontalScrollBarPolicy( 48 | ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); 49 | 50 | JButton nextButton = new JButton("Next Card"); 51 | cardList = new ArrayList(); 52 | JLabel qLabel = new JLabel("Question:"); 53 | JLabel aLabel = new JLabel("Answer:"); 54 | 55 | mainPanel.add(qLabel); 56 | mainPanel.add(qScroller); 57 | mainPanel.add(aLabel); 58 | mainPanel.add(aScroller); 59 | mainPanel.add(nextButton); 60 | nextButton.addActionListener(new NextCardListener()); 61 | JMenuBar menuBar = new JMenuBar(); 62 | JMenu fileMenu = new JMenu("File"); 63 | JMenuItem newMenuItem = new JMenuItem("New"); 64 | 65 | JMenuItem saveMenuItem = new JMenuItem("Save"); 66 | newMenuItem.addActionListener(new NewMenuListener()); 67 | saveMenuItem.addActionListener(new SaveMenuListener()); 68 | 69 | fileMenu.add(newMenuItem); 70 | fileMenu.add(saveMenuItem); 71 | menuBar.add(fileMenu); 72 | frame.setJMenuBar(menuBar); 73 | 74 | frame.getContentPane().add(BorderLayout.CENTER, mainPanel); 75 | frame.setSize(500,600); 76 | frame.setVisible(true); 77 | } 78 | 79 | 80 | public class NextCardListener implements ActionListener { 81 | public void actionPerformed(ActionEvent ev) { 82 | QuizCard card = new QuizCard(question.getText(), answer.getText()); 83 | cardList.add(card); 84 | clearCard(); 85 | 86 | } 87 | } 88 | 89 | public class SaveMenuListener implements ActionListener { 90 | public void actionPerformed(ActionEvent ev) { 91 | QuizCard card = new QuizCard(question.getText(), answer.getText()); 92 | cardList.add(card); 93 | 94 | JFileChooser fileSave = new JFileChooser(); 95 | fileSave.showSaveDialog(frame); 96 | saveFile(fileSave.getSelectedFile()); 97 | } 98 | } 99 | 100 | public class NewMenuListener implements ActionListener { 101 | public void actionPerformed(ActionEvent ev) { 102 | cardList.clear(); 103 | clearCard(); 104 | } 105 | } 106 | 107 | 108 | private void clearCard() { 109 | question.setText(""); 110 | answer.setText(""); 111 | question.requestFocus(); 112 | } 113 | 114 | private void saveFile(File file) { 115 | 116 | try { 117 | BufferedWriter writer = new BufferedWriter(new FileWriter(file)); 118 | Iterator cardIterator = cardList.iterator(); 119 | while (cardIterator.hasNext()) { 120 | QuizCard card = (QuizCard) cardIterator.next(); 121 | writer.write(card.getQuestion() + "/"); 122 | writer.write(card.getAnswer() + "\n"); 123 | } 124 | writer.close(); 125 | 126 | 127 | } catch(IOException ex) { 128 | System.out.println("couldn't write the cardList out"); 129 | ex.printStackTrace(); 130 | } 131 | 132 | } // close method 133 | } 134 | 135 | 136 | 137 | 138 | -------------------------------------------------------------------------------- /chap14/QuizCardReader$NextCardListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/QuizCardReader$NextCardListener.class -------------------------------------------------------------------------------- /chap14/QuizCardReader$OpenMenuListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/QuizCardReader$OpenMenuListener.class -------------------------------------------------------------------------------- /chap14/QuizCardReader.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap14/QuizCardReader.class -------------------------------------------------------------------------------- /chap14/QuizCardReader.java: -------------------------------------------------------------------------------- 1 | package chap14; 2 | import java.util.*; 3 | import java.awt.event.*; 4 | import javax.swing.*; 5 | import java.awt.*; 6 | import java.io.*; 7 | 8 | public class QuizCardReader { 9 | 10 | private JTextArea display; 11 | private JTextArea answer; 12 | private ArrayList cardList; 13 | private QuizCard currentCard; 14 | private Iterator cardIterator; 15 | private JFrame frame; 16 | private JButton nextButton; 17 | private boolean isShowAnswer; 18 | 19 | // additional, bonus method not found in any book! 20 | 21 | public static void main (String[] args) { 22 | QuizCardReader qReader = new QuizCardReader(); 23 | qReader.go(); 24 | } 25 | 26 | public void go() { 27 | 28 | frame = new JFrame("Quiz Card Player"); 29 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 30 | JPanel mainPanel = new JPanel(); 31 | Font bigFont = new Font("sanserif", Font.BOLD, 24); 32 | 33 | display = new JTextArea(9,20); 34 | display.setFont(bigFont); 35 | display.setLineWrap(true); 36 | display.setWrapStyleWord(true); 37 | display.setEditable(false); 38 | 39 | JScrollPane qScroller = new JScrollPane(display); 40 | qScroller.setVerticalScrollBarPolicy( 41 | ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 42 | qScroller.setHorizontalScrollBarPolicy( 43 | ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); 44 | 45 | nextButton = new JButton("Show Question"); 46 | 47 | mainPanel.add(qScroller); 48 | mainPanel.add(nextButton); 49 | nextButton.addActionListener(new NextCardListener()); 50 | JMenuBar menuBar = new JMenuBar(); 51 | JMenu fileMenu = new JMenu("File"); 52 | 53 | JMenuItem loadMenuItem = new JMenuItem("Load card set"); 54 | 55 | loadMenuItem.addActionListener(new OpenMenuListener()); 56 | 57 | fileMenu.add(loadMenuItem); 58 | 59 | menuBar.add(fileMenu); 60 | frame.setJMenuBar(menuBar); 61 | 62 | frame.getContentPane().add(BorderLayout.CENTER, mainPanel); 63 | frame.setSize(500,600); 64 | frame.setVisible(true); 65 | } // close go 66 | 67 | 68 | public class NextCardListener implements ActionListener { 69 | public void actionPerformed(ActionEvent ev) { 70 | if (isShowAnswer) { 71 | // show the answer because they've seen the question 72 | display.setText(currentCard.getAnswer()); 73 | nextButton.setText("Next Card"); 74 | isShowAnswer = false; 75 | } else { 76 | // show the next question 77 | if (cardIterator.hasNext()) { 78 | 79 | showNextCard(); 80 | 81 | } else { 82 | // there are no more cards! 83 | display.setText("That was last card"); 84 | nextButton.disable(); 85 | } 86 | } // close if 87 | } // close method 88 | } // close inner class 89 | 90 | 91 | public class OpenMenuListener implements ActionListener { 92 | public void actionPerformed(ActionEvent ev) { 93 | JFileChooser fileOpen = new JFileChooser(); 94 | fileOpen.showOpenDialog(frame); 95 | loadFile(fileOpen.getSelectedFile()); 96 | } 97 | } 98 | 99 | private void loadFile(File file) { 100 | cardList = new ArrayList(); 101 | try { 102 | BufferedReader reader = new BufferedReader(new FileReader(file)); 103 | String line = null; 104 | while ((line = reader.readLine()) != null) { 105 | makeCard(line); 106 | } 107 | reader.close(); 108 | 109 | } catch(Exception ex) { 110 | System.out.println("couldn't read the card file"); 111 | ex.printStackTrace(); 112 | } 113 | 114 | // now time to start 115 | cardIterator = cardList.iterator(); 116 | showNextCard(); 117 | } 118 | 119 | private void makeCard(String lineToParse) { 120 | 121 | StringTokenizer parser = new StringTokenizer(lineToParse, "/"); 122 | if (parser.hasMoreTokens()) { 123 | QuizCard card = new QuizCard(parser.nextToken(), parser.nextToken()); 124 | cardList.add(card); 125 | } 126 | } 127 | 128 | private void showNextCard() { 129 | currentCard = (QuizCard) cardIterator.next(); 130 | display.setText(currentCard.getQuestion()); 131 | nextButton.setText("Show Answer"); 132 | isShowAnswer = true; 133 | } 134 | } // close class 135 | 136 | 137 | 138 | 139 | -------------------------------------------------------------------------------- /chap15/BankAccount.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap15/BankAccount.class -------------------------------------------------------------------------------- /chap15/DailyAdviceClient.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap15/DailyAdviceClient.class -------------------------------------------------------------------------------- /chap15/DailyAdviceClient.java: -------------------------------------------------------------------------------- 1 | package chap15; 2 | 3 | import java.io.*; 4 | import java.net.*; 5 | 6 | public class DailyAdviceClient 7 | { 8 | public void go() { 9 | try { 10 | Socket s = new Socket("127.0.0.1", 4242); 11 | InputStreamReader streamReader = new InputStreamReader(s.getInputStream()); 12 | BufferedReader reader = new BufferedReader(streamReader); 13 | 14 | String advice = reader.readLine(); 15 | System.out.println("Today you should: " + advice); 16 | reader.close(); 17 | } 18 | catch (IOException ex) 19 | { 20 | ex.printStackTrace(); 21 | } 22 | } 23 | 24 | public static void main(String[] args) 25 | { 26 | DailyAdviceClient client = new DailyAdviceClient(); 27 | client.go(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /chap15/DailyAdviceServer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap15/DailyAdviceServer.class -------------------------------------------------------------------------------- /chap15/DailyAdviceServer.java: -------------------------------------------------------------------------------- 1 | package chap15; 2 | import java.io.*; 3 | import java.net.*; 4 | 5 | public class DailyAdviceServer 6 | { 7 | String[] adviceList = {"Take smaller bites", "Go for the tight jeans. No they do NOT make you look fat", 8 | "One word: inappropriate", "Just for today, be honest. Tell your boss what you *really* think", 9 | "You might want to rethink that haircut"}; 10 | 11 | public void go() { 12 | try { 13 | ServerSocket serverSock = new ServerSocket(4242); 14 | while (true) 15 | { 16 | Socket sock = serverSock.accept(); 17 | 18 | PrintWriter writer = new PrintWriter(sock.getOutputStream()); 19 | String advice = getAdvice(); 20 | writer.println(advice); 21 | writer.close(); 22 | System.out.println(advice); 23 | } 24 | } catch (IOException ex) 25 | { 26 | ex.printStackTrace(); 27 | } 28 | } 29 | 30 | private String getAdvice() { 31 | int random = (int) (Math.random() * adviceList.length); 32 | return adviceList[random]; 33 | } 34 | 35 | public static void main(String[] args) 36 | { 37 | DailyAdviceServer server = new DailyAdviceServer(); 38 | server.go(); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /chap15/MyRunnable.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap15/MyRunnable.class -------------------------------------------------------------------------------- /chap15/MyRunnable.java: -------------------------------------------------------------------------------- 1 | package chap15; 2 | 3 | public class MyRunnable implements Runnable 4 | { 5 | 6 | public void run() 7 | { 8 | go(); 9 | } 10 | 11 | public void go() { 12 | 13 | //* 14 | try { 15 | Thread.sleep(2000); 16 | } catch (InterruptedException ex) 17 | { 18 | ex.printStackTrace(); 19 | }//*/ 20 | 21 | doMore(); 22 | } 23 | 24 | public void doMore() { 25 | System.out.println("top o' the stack"); 26 | } 27 | 28 | 29 | public static void main(String[] args) 30 | { 31 | Runnable threadJob = new MyRunnable(); 32 | Thread myThread = new Thread(threadJob); 33 | myThread.start(); 34 | System.out.println("back in main"); 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /chap15/RunThreads.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap15/RunThreads.class -------------------------------------------------------------------------------- /chap15/RunThreads.java: -------------------------------------------------------------------------------- 1 | package chap15; 2 | 3 | public class RunThreads implements Runnable 4 | { 5 | public static void main(String[] args) { 6 | RunThreads runner = new RunThreads(); 7 | Thread alpha = new Thread(runner); 8 | Thread beta = new Thread(runner); 9 | alpha.setName("Alpha thread"); 10 | beta.setName("Beta thread"); 11 | alpha.start(); 12 | beta.start(); 13 | } 14 | 15 | public void run() { 16 | for (int i = 0; i < 25; i++) 17 | { 18 | String threadName = Thread.currentThread().getName(); 19 | System.out.println(threadName + " is running"); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /chap15/RyanAndMonicaJob.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap15/RyanAndMonicaJob.class -------------------------------------------------------------------------------- /chap15/RyanAndMonicaJob.java: -------------------------------------------------------------------------------- 1 | package chap15; 2 | 3 | public class RyanAndMonicaJob implements Runnable 4 | { 5 | private BankAccount account = new BankAccount(); 6 | 7 | public static void main(String[] args) { 8 | RyanAndMonicaJob theJob = new RyanAndMonicaJob(); 9 | Thread one = new Thread(theJob); 10 | Thread two = new Thread(theJob); 11 | one.setName("Ryan"); 12 | two.setName("Monica"); 13 | one.start(); 14 | two.start(); 15 | } 16 | 17 | public void run() 18 | { 19 | for (int x = 0; x < 10; x++) { 20 | makeWithdrawal(10); 21 | if (account.getBalance() < 0) 22 | { 23 | System.out.println("Overdrawn!"); 24 | } 25 | } 26 | } 27 | // to demonstrate the "overdrawn" error remove the "synchronized" modifier 28 | private synchronized void makeWithdrawal(int amount) 29 | { 30 | if (account.getBalance() >= amount) 31 | { 32 | System.out.println(Thread.currentThread().getName() + " is about to withdrawal"); 33 | try { 34 | System.out.println(Thread.currentThread().getName() + " is going to sleep"); 35 | Thread.sleep(500); 36 | } catch (InterruptedException ex) { ex.printStackTrace(); } 37 | System.out.println(Thread.currentThread().getName() + " woke up"); 38 | account.withdraw(amount); 39 | System.out.println(Thread.currentThread().getName() + " completes the withdrawal"); 40 | } 41 | else 42 | { 43 | System.out.println("Sorry, not enough for " + Thread.currentThread().getName()); 44 | } 45 | } 46 | 47 | } 48 | 49 | 50 | class BankAccount { 51 | private int balance = 100; 52 | 53 | public int getBalance () { 54 | return balance; 55 | } 56 | 57 | public void withdraw(int amount) { 58 | balance = balance - amount; 59 | } 60 | } -------------------------------------------------------------------------------- /chap15/SimpleChatClient$IncomingReader.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap15/SimpleChatClient$IncomingReader.class -------------------------------------------------------------------------------- /chap15/SimpleChatClient$SendButtonListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap15/SimpleChatClient$SendButtonListener.class -------------------------------------------------------------------------------- /chap15/SimpleChatClient.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap15/SimpleChatClient.class -------------------------------------------------------------------------------- /chap15/SimpleChatClient.java: -------------------------------------------------------------------------------- 1 | package chap15; 2 | import java.io.*; 3 | import java.net.*; 4 | import javax.swing.*; 5 | import java.awt.*; 6 | import java.awt.event.*; 7 | 8 | 9 | public class SimpleChatClient 10 | { 11 | JTextArea incoming; 12 | JTextField outgoing; 13 | BufferedReader reader; 14 | PrintWriter writer; 15 | Socket sock; 16 | 17 | public void go() { 18 | JFrame frame = new JFrame("Ludicrously Simple Chat Client"); 19 | JPanel mainPanel = new JPanel(); 20 | incoming = new JTextArea(15, 50); 21 | incoming.setLineWrap(true); 22 | incoming.setWrapStyleWord(true); 23 | incoming.setEditable(false); 24 | JScrollPane qScroller = new JScrollPane(incoming); 25 | qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 26 | qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); 27 | outgoing = new JTextField(20); 28 | JButton sendButton = new JButton("Send"); 29 | sendButton.addActionListener(new SendButtonListener()); 30 | mainPanel.add(qScroller); 31 | mainPanel.add(outgoing); 32 | mainPanel.add(sendButton); 33 | frame.getContentPane().add(BorderLayout.CENTER, mainPanel); 34 | setUpNetworking(); 35 | 36 | Thread readerThread = new Thread(new IncomingReader()); 37 | readerThread.start(); 38 | 39 | frame.setSize(650, 500); 40 | frame.setVisible(true); 41 | 42 | } 43 | 44 | private void setUpNetworking() { 45 | try { 46 | sock = new Socket("127.0.0.1", 5000); 47 | InputStreamReader streamReader = new InputStreamReader(sock.getInputStream()); 48 | reader = new BufferedReader(streamReader); 49 | writer = new PrintWriter(sock.getOutputStream()); 50 | System.out.println("networking established"); 51 | } 52 | catch(IOException ex) 53 | { 54 | ex.printStackTrace(); 55 | } 56 | } 57 | 58 | public class SendButtonListener implements ActionListener { 59 | public void actionPerformed(ActionEvent ev) { 60 | try { 61 | writer.println(outgoing.getText()); 62 | writer.flush(); 63 | 64 | } 65 | catch (Exception ex) { 66 | ex.printStackTrace(); 67 | } 68 | outgoing.setText(""); 69 | outgoing.requestFocus(); 70 | } 71 | } 72 | 73 | public static void main(String[] args) { 74 | new SimpleChatClient().go(); 75 | } 76 | 77 | class IncomingReader implements Runnable { 78 | public void run() { 79 | String message; 80 | try { 81 | while ((message = reader.readLine()) != null) { 82 | System.out.println("client read " + message); 83 | incoming.append(message + "\n"); 84 | } 85 | } catch (IOException ex) 86 | { 87 | ex.printStackTrace(); 88 | } 89 | } 90 | } 91 | } 92 | 93 | -------------------------------------------------------------------------------- /chap15/SimpleChatClientA$SendButtonListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap15/SimpleChatClientA$SendButtonListener.class -------------------------------------------------------------------------------- /chap15/SimpleChatClientA.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap15/SimpleChatClientA.class -------------------------------------------------------------------------------- /chap15/SimpleChatClientA.java: -------------------------------------------------------------------------------- 1 | package chap15; 2 | import java.io.*; 3 | import java.net.*; 4 | import javax.swing.*; 5 | import java.awt.*; 6 | import java.awt.event.*; 7 | 8 | 9 | public class SimpleChatClientA 10 | { 11 | JTextField outgoing; 12 | PrintWriter writer; 13 | Socket sock; 14 | 15 | public void go() { 16 | JFrame frame = new JFrame("Ludicrously Simple Chat Client"); 17 | JPanel mainPanel = new JPanel(); 18 | outgoing = new JTextField(20); 19 | JButton sendButton = new JButton("Send"); 20 | sendButton.addActionListener(new SendButtonListener()); 21 | mainPanel.add(outgoing); 22 | mainPanel.add(sendButton); 23 | frame.getContentPane().add(BorderLayout.CENTER, mainPanel); 24 | setUpNetworking(); 25 | frame.setSize(400, 500); 26 | frame.setVisible(true); 27 | 28 | } 29 | 30 | private void setUpNetworking() { 31 | try { 32 | sock = new Socket("127.0.0.1", 5000); 33 | writer = new PrintWriter(sock.getOutputStream()); 34 | System.out.println("networking established"); 35 | } 36 | catch(IOException ex) 37 | { 38 | ex.printStackTrace(); 39 | } 40 | } 41 | 42 | public class SendButtonListener implements ActionListener { 43 | public void actionPerformed(ActionEvent ev) { 44 | try { 45 | writer.println(outgoing.getText()); 46 | writer.flush(); 47 | 48 | } 49 | catch (Exception ex) { 50 | ex.printStackTrace(); 51 | } 52 | outgoing.setText(""); 53 | outgoing.requestFocus(); 54 | } 55 | } 56 | 57 | public static void main(String[] args) { 58 | new SimpleChatClientA().go(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /chap15/VerySimpleChatServer$ClientHandler.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap15/VerySimpleChatServer$ClientHandler.class -------------------------------------------------------------------------------- /chap15/VerySimpleChatServer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap15/VerySimpleChatServer.class -------------------------------------------------------------------------------- /chap15/VerySimpleChatServer.java: -------------------------------------------------------------------------------- 1 | package chap15; 2 | import java.io.*; 3 | import java.net.*; 4 | import java.util.*; 5 | 6 | 7 | public class VerySimpleChatServer 8 | { 9 | ArrayList clientOutputStreams; 10 | 11 | public class ClientHandler implements Runnable { 12 | BufferedReader reader; 13 | Socket sock; 14 | 15 | public ClientHandler(Socket clientSOcket) { 16 | try { 17 | sock = clientSOcket; 18 | InputStreamReader isReader = new InputStreamReader(sock.getInputStream()); 19 | reader = new BufferedReader(isReader); 20 | 21 | } catch (Exception ex) { ex.printStackTrace(); } 22 | } 23 | 24 | public void run() { 25 | String message; 26 | try { 27 | while ((message = reader.readLine()) != null) { 28 | System.out.println("read " + message); 29 | tellEveryone(message); 30 | } 31 | } catch (Exception ex) { ex.printStackTrace(); } 32 | } 33 | } 34 | 35 | public static void main(String[] args) { 36 | new VerySimpleChatServer().go(); 37 | } 38 | 39 | public void go() { 40 | clientOutputStreams = new ArrayList(); 41 | try { 42 | ServerSocket serverSock = new ServerSocket(5000); 43 | while(true) { 44 | Socket clientSocket = serverSock.accept(); 45 | PrintWriter writer = new PrintWriter(clientSocket.getOutputStream()); 46 | clientOutputStreams.add(writer); 47 | 48 | Thread t = new Thread(new ClientHandler(clientSocket)); 49 | t.start(); 50 | System.out.println("got a connection"); 51 | } 52 | } catch (Exception ex) { ex.printStackTrace(); } 53 | } 54 | 55 | public void tellEveryone(String message) { 56 | Iterator it = clientOutputStreams.iterator(); 57 | while (it.hasNext()) { 58 | try { 59 | PrintWriter writer = (PrintWriter) it.next(); 60 | writer.println(message); 61 | writer.flush(); 62 | } catch (Exception ex) { ex.printStackTrace(); } 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /chap16/Jukebox1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap16/Jukebox1.class -------------------------------------------------------------------------------- /chap16/Jukebox1.java: -------------------------------------------------------------------------------- 1 | package chap16; 2 | 3 | import java.util.*; 4 | import java.io.*; 5 | 6 | public class Jukebox1 7 | { 8 | ArrayList songList = new ArrayList(); 9 | 10 | public static void main(String[] args) { 11 | new Jukebox1().go(); 12 | } 13 | 14 | public void go() { 15 | getSongs(); 16 | System.out.println(songList); 17 | } 18 | 19 | void getSongs() { 20 | try { 21 | File file = new File("SongList.txt"); 22 | BufferedReader reader = new BufferedReader(new FileReader(file)); 23 | String line = null; 24 | while ((line = reader.readLine()) != null) { 25 | addSong(line); 26 | } 27 | } catch (Exception ex) { ex.printStackTrace(); } 28 | } 29 | 30 | void addSong(String lineToParse) { 31 | String[]tokens = lineToParse.split("/"); 32 | songList.add(tokens[0]); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /chap16/Jukebox3.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap16/Jukebox3.class -------------------------------------------------------------------------------- /chap16/Jukebox3.java: -------------------------------------------------------------------------------- 1 | package chap16; 2 | 3 | import java.util.*; 4 | import java.io.*; 5 | 6 | public class Jukebox3 7 | { 8 | ArrayList songList = new ArrayList(); 9 | 10 | public static void main(String[] args) { 11 | new Jukebox3().go(); 12 | } 13 | 14 | public void go() { 15 | getSongs(); 16 | System.out.println(songList); 17 | Collections.sort(songList); 18 | System.out.println(songList); 19 | } 20 | 21 | void getSongs() { 22 | try { 23 | File file = new File("SongList.txt"); 24 | BufferedReader reader = new BufferedReader(new FileReader(file)); 25 | String line = null; 26 | while ((line = reader.readLine()) != null) { 27 | addSong(line); 28 | } 29 | } catch (Exception ex) { ex.printStackTrace(); } 30 | } 31 | 32 | void addSong(String lineToParse) { 33 | String[]tokens = lineToParse.split("/"); 34 | Song nextSong = new Song(tokens[0], tokens[1], tokens[2], tokens[3]); 35 | songList.add(nextSong); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /chap16/Jukebox5$ArtistCompare.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap16/Jukebox5$ArtistCompare.class -------------------------------------------------------------------------------- /chap16/Jukebox5.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap16/Jukebox5.class -------------------------------------------------------------------------------- /chap16/Jukebox5.java: -------------------------------------------------------------------------------- 1 | package chap16; 2 | 3 | import java.util.*; 4 | import java.io.*; 5 | 6 | public class Jukebox5 7 | { 8 | ArrayList songList = new ArrayList(); 9 | 10 | public static void main(String[] args) { 11 | new Jukebox5().go(); 12 | } 13 | class ArtistCompare implements Comparator { 14 | public int compare(Song one, Song two) { 15 | return one.getArtist().compareTo(two.getArtist()); 16 | } 17 | } 18 | 19 | public void go() { 20 | getSongs(); 21 | System.out.println(songList); 22 | Collections.sort(songList); 23 | System.out.println(songList); 24 | 25 | ArtistCompare artistCompare = new ArtistCompare(); 26 | Collections.sort(songList, artistCompare); 27 | 28 | System.out.println(songList); 29 | } 30 | 31 | void getSongs() { 32 | try { 33 | File file = new File("SongListMore.txt"); 34 | BufferedReader reader = new BufferedReader(new FileReader(file)); 35 | String line = null; 36 | while ((line = reader.readLine()) != null) { 37 | addSong(line); 38 | } 39 | } catch (Exception ex) { ex.printStackTrace(); } 40 | } 41 | 42 | void addSong(String lineToParse) { 43 | String[]tokens = lineToParse.split("/"); 44 | Song nextSong = new Song(tokens[0], tokens[1], tokens[2], tokens[3]); 45 | songList.add(nextSong); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /chap16/Jukebox6.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap16/Jukebox6.class -------------------------------------------------------------------------------- /chap16/Jukebox6.java: -------------------------------------------------------------------------------- 1 | package chap16; 2 | 3 | import java.util.*; 4 | import java.io.*; 5 | 6 | public class Jukebox6 7 | { 8 | ArrayList songList = new ArrayList(); 9 | 10 | public static void main(String[] args) { 11 | new Jukebox6().go(); 12 | } 13 | 14 | public void go() { 15 | getSongs(); 16 | System.out.println(songList); 17 | Collections.sort(songList); 18 | System.out.println(songList); 19 | 20 | HashSet songSet = new HashSet(); 21 | songSet.addAll(songList); 22 | System.out.println(songSet); 23 | } 24 | 25 | void getSongs() { 26 | try { 27 | File file = new File("SongListMore.txt"); 28 | BufferedReader reader = new BufferedReader(new FileReader(file)); 29 | String line = null; 30 | while ((line = reader.readLine()) != null) { 31 | addSong(line); 32 | } 33 | } catch (Exception ex) { ex.printStackTrace(); } 34 | } 35 | 36 | void addSong(String lineToParse) { 37 | String[]tokens = lineToParse.split("/"); 38 | SongBad nextSong = new SongBad(tokens[0], tokens[1], tokens[2], tokens[3]); 39 | songList.add(nextSong); 40 | } 41 | } 42 | 43 | 44 | class SongBad implements Comparable 45 | { 46 | String title; 47 | String artist; 48 | String rating; 49 | String bpm; 50 | 51 | 52 | public SongBad(String t, String a, String r, String b) { 53 | title = t; 54 | artist = a; 55 | rating = r; 56 | bpm = b; 57 | } 58 | public boolean equals(Object aSong) { 59 | SongBad s = (SongBad) aSong; 60 | return getTitle().equals(s.getTitle()); 61 | } 62 | 63 | //leaving this out makes this a bad form of song. Uncomment this to get rid of the duplicates 64 | /*public int hashCode() { 65 | return title.hashCode(); 66 | } 67 | */ 68 | 69 | public int compareTo(SongBad s) 70 | { 71 | return title.compareTo(s.getTitle()); 72 | } 73 | 74 | public String getArtist() 75 | { 76 | return artist; 77 | } 78 | 79 | public String getBpm() 80 | { 81 | return bpm; 82 | } 83 | 84 | public String getRating() 85 | { 86 | return rating; 87 | } 88 | 89 | public String getTitle() 90 | { 91 | return title; 92 | } 93 | 94 | public String toString() { 95 | return title; 96 | } 97 | 98 | } -------------------------------------------------------------------------------- /chap16/Jukebox8.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap16/Jukebox8.class -------------------------------------------------------------------------------- /chap16/Jukebox8.java: -------------------------------------------------------------------------------- 1 | package chap16; 2 | 3 | import java.util.*; 4 | import java.io.*; 5 | 6 | public class Jukebox8 7 | { 8 | ArrayList songList = new ArrayList(); 9 | 10 | public static void main(String[] args) { 11 | new Jukebox8().go(); 12 | } 13 | 14 | public void go() { 15 | getSongs(); 16 | System.out.println(songList); 17 | Collections.sort(songList); 18 | System.out.println(songList); 19 | 20 | TreeSet songSet = new TreeSet(); 21 | songSet.addAll(songList); 22 | System.out.println(songSet); 23 | } 24 | 25 | void getSongs() { 26 | try { 27 | File file = new File("SongListMore.txt"); 28 | BufferedReader reader = new BufferedReader(new FileReader(file)); 29 | String line = null; 30 | while ((line = reader.readLine()) != null) { 31 | addSong(line); 32 | } 33 | } catch (Exception ex) { ex.printStackTrace(); } 34 | } 35 | 36 | void addSong(String lineToParse) { 37 | String[]tokens = lineToParse.split("/"); 38 | Song nextSong = new Song(tokens[0], tokens[1], tokens[2], tokens[3]); 39 | songList.add(nextSong); 40 | } 41 | } -------------------------------------------------------------------------------- /chap16/Song.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap16/Song.class -------------------------------------------------------------------------------- /chap16/Song.java: -------------------------------------------------------------------------------- 1 | package chap16; 2 | 3 | public class Song implements Comparable 4 | { 5 | String title; 6 | String artist; 7 | String rating; 8 | String bpm; 9 | 10 | 11 | public Song(String t, String a, String r, String b) { 12 | title = t; 13 | artist = a; 14 | rating = r; 15 | bpm = b; 16 | } 17 | public boolean equals(Object aSong) { 18 | Song s = (Song) aSong; 19 | return getTitle().equals(s.getTitle()); 20 | } 21 | 22 | public int hashCode() { 23 | return title.hashCode(); 24 | } 25 | 26 | public int compareTo(Song s) 27 | { 28 | return title.compareTo(s.getTitle()); 29 | } 30 | 31 | public String getArtist() 32 | { 33 | return artist; 34 | } 35 | 36 | public String getBpm() 37 | { 38 | return bpm; 39 | } 40 | 41 | public String getRating() 42 | { 43 | return rating; 44 | } 45 | 46 | public String getTitle() 47 | { 48 | return title; 49 | } 50 | 51 | public String toString() { 52 | return title; 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /chap18/DayOfTheWeekService$DoItListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap18/DayOfTheWeekService$DoItListener.class -------------------------------------------------------------------------------- /chap18/DayOfTheWeekService.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap18/DayOfTheWeekService.class -------------------------------------------------------------------------------- /chap18/DayOfTheWeekService.java: -------------------------------------------------------------------------------- 1 | package chap18; 2 | import javax.swing.*; 3 | import java.awt.event.*; 4 | import java.awt.*; 5 | import java.io.*; 6 | import java.util.*; 7 | import java.text.*; 8 | 9 | public class DayOfTheWeekService implements Service { 10 | 11 | JLabel outputLabel; 12 | JComboBox month; 13 | JTextField day; 14 | JTextField year; 15 | 16 | public JPanel getGuiPanel() { 17 | JPanel panel = new JPanel(); 18 | JButton button = new JButton("Do it!"); 19 | button.addActionListener(new DoItListener()); 20 | outputLabel = new JLabel("date appears here"); 21 | 22 | DateFormatSymbols dateStuff = new DateFormatSymbols(); 23 | month = new JComboBox(dateStuff.getMonths()); 24 | day = new JTextField(8); 25 | year = new JTextField(8); 26 | 27 | JPanel inputPanel = new JPanel(new GridLayout(3,2)); 28 | inputPanel.add(new JLabel("Month")); 29 | inputPanel.add(month); 30 | inputPanel.add(new JLabel("Day")); 31 | inputPanel.add(day); 32 | inputPanel.add(new JLabel("Year")); 33 | inputPanel.add(year); 34 | 35 | panel.add(inputPanel); 36 | panel.add(button); 37 | panel.add(outputLabel); 38 | return panel; 39 | } 40 | 41 | public class DoItListener implements ActionListener { 42 | public void actionPerformed(ActionEvent ev) { 43 | int monthNum = month.getSelectedIndex(); 44 | int dayNum = Integer.parseInt(day.getText()); 45 | int yearNum = Integer.parseInt(year.getText()); 46 | Calendar c = Calendar.getInstance(); 47 | c.set(Calendar.MONTH, monthNum); 48 | c.set(Calendar.DAY_OF_MONTH, dayNum); 49 | c.set(Calendar.YEAR, yearNum); 50 | Date date = c.getTime(); 51 | String dayOfWeek = (new SimpleDateFormat("EEEE")).format(date); 52 | outputLabel.setText(dayOfWeek); 53 | 54 | 55 | } 56 | } 57 | 58 | } 59 | 60 | 61 | -------------------------------------------------------------------------------- /chap18/DiceService$RollEmListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap18/DiceService$RollEmListener.class -------------------------------------------------------------------------------- /chap18/DiceService.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap18/DiceService.class -------------------------------------------------------------------------------- /chap18/DiceService.java: -------------------------------------------------------------------------------- 1 | package chap18; 2 | import javax.swing.*; 3 | import java.awt.event.*; 4 | import java.io.*; 5 | 6 | public class DiceService implements Service { 7 | 8 | JLabel label; 9 | JComboBox numOfDice; 10 | 11 | public JPanel getGuiPanel() { 12 | JPanel panel = new JPanel(); 13 | JButton button = new JButton("Roll 'em!"); 14 | String[] choices = {"1", "2", "3", "4", "5"}; 15 | numOfDice = new JComboBox(choices); 16 | label = new JLabel("dice values here"); 17 | button.addActionListener(new RollEmListener()); 18 | panel.add(numOfDice); 19 | panel.add(button); 20 | panel.add(label); 21 | return panel; 22 | } 23 | 24 | public class RollEmListener implements ActionListener { 25 | public void actionPerformed(ActionEvent ev) { 26 | // roll the dice 27 | String diceOutput = ""; 28 | String selection = (String) numOfDice.getSelectedItem(); 29 | int numOfDiceToRoll = Integer.parseInt(selection); 30 | for (int i = 0; i < numOfDiceToRoll; i++) { 31 | int r = (int) ((Math.random() * 6) + 1); 32 | diceOutput += (" " + r); 33 | } 34 | label.setText(diceOutput); 35 | 36 | } 37 | } 38 | 39 | } 40 | 41 | 42 | -------------------------------------------------------------------------------- /chap18/KathyServlet.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap18/KathyServlet.class -------------------------------------------------------------------------------- /chap18/KathyServlet.java: -------------------------------------------------------------------------------- 1 | package chap18; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class KathyServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out; String title = "PhraseOMatic has generated the following phrase."; response.setContentType("text/html"); out = response.getWriter(); out.println(""); out.println("PhraseOmatic"); out.println(""); out.println("

" + title + "

"); out.println("

" + PhraseOMatic2.makePhrase()); 2 | out.println("

make another phrase

"); out.println(""); 3 | out.close(); } } -------------------------------------------------------------------------------- /chap18/MiniMusicService$MyDrawPanel.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap18/MiniMusicService$MyDrawPanel.class -------------------------------------------------------------------------------- /chap18/MiniMusicService$PlayItListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap18/MiniMusicService$PlayItListener.class -------------------------------------------------------------------------------- /chap18/MiniMusicService.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap18/MiniMusicService.class -------------------------------------------------------------------------------- /chap18/MiniMusicService.java: -------------------------------------------------------------------------------- 1 | package chap18; 2 | import javax.sound.midi.*; 3 | import java.io.*; 4 | import javax.swing.*; 5 | import java.awt.*; 6 | import java.awt.event.*; 7 | 8 | 9 | public class MiniMusicService implements Service { 10 | 11 | 12 | MyDrawPanel myPanel; 13 | 14 | 15 | public JPanel getGuiPanel() { 16 | 17 | JPanel mainPanel = new JPanel(); 18 | myPanel = new MyDrawPanel(); 19 | JButton playItButton = new JButton("Play it"); 20 | playItButton.addActionListener(new PlayItListener()); 21 | mainPanel.add(myPanel); 22 | mainPanel.add(playItButton); 23 | return mainPanel; 24 | } 25 | 26 | 27 | public class PlayItListener implements ActionListener { 28 | public void actionPerformed(ActionEvent ev) { 29 | 30 | try { 31 | 32 | // make (and open) a sequencer, make a sequence and track 33 | 34 | Sequencer sequencer = MidiSystem.getSequencer(); 35 | sequencer.open(); 36 | 37 | sequencer.addControllerEventListener(myPanel, new int[] {127}); 38 | Sequence seq = new Sequence(Sequence.PPQ, 4); 39 | Track track = seq.createTrack(); 40 | 41 | // now make two midi events (containing a midi message) 42 | 43 | 44 | 45 | for (int i = 0; i < 100; i+= 4) { 46 | 47 | int rNum = (int) ((Math.random() * 50) + 1); 48 | if (rNum < 38) { // so now only do it if num <38 (75% of the time) 49 | 50 | track.add(makeEvent(144,1,rNum,100,i)); 51 | 52 | track.add(makeEvent(176,1,127,0,i)); 53 | 54 | track.add(makeEvent(128,1,rNum,100,i + 2)); 55 | } 56 | } // end loop 57 | 58 | // add the events to the track 59 | // add the sequence to the sequencer, set timing, and start 60 | 61 | sequencer.setSequence(seq); 62 | 63 | sequencer.start(); 64 | sequencer.setTempoInBPM(220); 65 | } catch (Exception ex) {ex.printStackTrace();} 66 | 67 | } // close actionperformed 68 | } // close inner class 69 | 70 | 71 | public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) { 72 | MidiEvent event = null; 73 | try { 74 | ShortMessage a = new ShortMessage(); 75 | a.setMessage(comd, chan, one, two); 76 | event = new MidiEvent(a, tick); 77 | 78 | }catch(Exception e) { } 79 | return event; 80 | } 81 | 82 | 83 | 84 | class MyDrawPanel extends JPanel implements ControllerEventListener { 85 | 86 | // only if we got an event do we want to paint 87 | boolean msg = false; 88 | 89 | public void controlChange(ShortMessage event) { 90 | msg = true; 91 | repaint(); 92 | } 93 | 94 | public Dimension getPreferredSize() { 95 | return new Dimension(300,300); 96 | } 97 | 98 | public void paintComponent(Graphics g) { 99 | if (msg) { 100 | 101 | Graphics2D g2 = (Graphics2D) g; 102 | 103 | int r = (int) (Math.random() * 250); 104 | int gr = (int) (Math.random() * 250); 105 | int b = (int) (Math.random() * 250); 106 | 107 | g.setColor(new Color(r,gr,b)); 108 | 109 | int ht = (int) ((Math.random() * 120) + 10); 110 | int width = (int) ((Math.random() * 120) + 10); 111 | 112 | int x = (int) ((Math.random() * 40) + 10); 113 | int y = (int) ((Math.random() * 40) + 10); 114 | 115 | g.fillRect(x,y,ht, width); 116 | msg = false; 117 | 118 | } // close if 119 | } // close method 120 | } // close inner class 121 | 122 | } // close class -------------------------------------------------------------------------------- /chap18/PhraseOMatic2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap18/PhraseOMatic2.class -------------------------------------------------------------------------------- /chap18/PhraseOMatic2.java: -------------------------------------------------------------------------------- 1 | package chap18; 2 | public class PhraseOMatic2 { 3 | public static String makePhrase() { 4 | 5 | // make three sets of words to choose from 6 | String[] wordListOne = {"24/7","multi-Tier","30,000 foot","B-to-B","win-win","front-end", "web-based","pervasive", "smart", "six-sigma","critical-path", "dynamic"}; 7 | 8 | String[] wordListTwo = {"empowered", "sticky", "valued-added", "oriented", "centric", "distributed", "clustered", "branded","outside-the-box", "positioned", "networked", "focused", "leveraged", "aligned", "targeted", "shared", "cooperative", "accelerated"}; 9 | 10 | String[] wordListThree = {"process", "tipping point", "solution", "architecture", "core competency", "strategy", "mindshare", "portal", "space", "vision", "paradigm", "mission"}; 11 | 12 | // find out how many words are in each list 13 | int oneLength = wordListOne.length; 14 | int twoLength = wordListTwo.length; 15 | int threeLength = wordListThree.length; 16 | 17 | // generate three random numbers, to pull random words from each list 18 | int rand1 = (int) (Math.random() * oneLength); 19 | int rand2 = (int) (Math.random() * twoLength); 20 | int rand3 = (int) (Math.random() * threeLength); 21 | 22 | // now build a phrase 23 | String phrase = wordListOne[rand1] + " " + wordListTwo[rand2] + " " + wordListThree[rand3]; 24 | 25 | // now return it 26 | return ("What we need is a " + phrase); 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /chap18/Service.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap18/Service.class -------------------------------------------------------------------------------- /chap18/Service.java: -------------------------------------------------------------------------------- 1 | package chap18; 2 | import javax.swing.*; 3 | import java.io.*; 4 | 5 | public interface Service extends Serializable { 6 | public JPanel getGuiPanel(); 7 | } -------------------------------------------------------------------------------- /chap18/ServiceBrowser$MyListListener.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap18/ServiceBrowser$MyListListener.class -------------------------------------------------------------------------------- /chap18/ServiceBrowser.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap18/ServiceBrowser.class -------------------------------------------------------------------------------- /chap18/ServiceBrowser.java: -------------------------------------------------------------------------------- 1 | package chap18; 2 | import java.awt.*; 3 | import javax.swing.*; 4 | import java.rmi.*; 5 | import java.awt.event.*; 6 | 7 | 8 | 9 | public class ServiceBrowser { 10 | 11 | JPanel mainPanel; 12 | JComboBox serviceList; 13 | ServiceServer server; 14 | 15 | public void buildGUI() { 16 | JFrame frame = new JFrame("RMI Browser"); 17 | mainPanel = new JPanel(); 18 | frame.getContentPane().add(BorderLayout.CENTER, mainPanel); 19 | 20 | Object[] services = getServicesList(); 21 | 22 | serviceList = new JComboBox(services); 23 | frame.getContentPane().add(BorderLayout.NORTH, serviceList); 24 | 25 | serviceList.addActionListener(new MyListListener()); 26 | 27 | frame.setSize(500,500); 28 | frame.setVisible(true); 29 | 30 | } 31 | 32 | void loadService(Object serviceSelection) { 33 | try { 34 | Service svc = server.getService(serviceSelection); 35 | 36 | mainPanel.removeAll(); 37 | mainPanel.add(svc.getGuiPanel()); 38 | mainPanel.validate(); 39 | mainPanel.repaint(); 40 | } catch(Exception ex) { 41 | ex.printStackTrace(); 42 | } 43 | } 44 | 45 | 46 | 47 | Object[] getServicesList() { 48 | 49 | Object obj = null; 50 | Object[] services = null; 51 | 52 | try { 53 | 54 | obj = Naming.lookup("rmi://127.0.0.1/ServiceServer"); 55 | 56 | } 57 | catch(Exception ex) { 58 | ex.printStackTrace(); 59 | } 60 | server = (ServiceServer) obj; 61 | 62 | 63 | try { 64 | 65 | services = server.getServiceList(); 66 | 67 | } catch(Exception ex) { 68 | ex.printStackTrace(); 69 | } 70 | return services; 71 | 72 | } 73 | 74 | class MyListListener implements ActionListener { 75 | public void actionPerformed(ActionEvent ev) { 76 | // do things to get the selected service 77 | Object selection = serviceList.getSelectedItem(); 78 | loadService(selection); 79 | } 80 | } 81 | 82 | public static void main(String[] args) { 83 | new ServiceBrowser().buildGUI(); 84 | } 85 | } 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /chap18/ServiceServer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap18/ServiceServer.class -------------------------------------------------------------------------------- /chap18/ServiceServer.java: -------------------------------------------------------------------------------- 1 | package chap18; 2 | import java.rmi.*; 3 | 4 | public interface ServiceServer extends Remote { 5 | 6 | Object[] getServiceList() throws RemoteException; 7 | 8 | Service getService(Object serviceKey) throws RemoteException; 9 | } -------------------------------------------------------------------------------- /chap18/ServiceServerImpl.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bethrobson/Head-First-Java/0eb013ed0a75c1270ed2e113eff559abfa66f086/chap18/ServiceServerImpl.class -------------------------------------------------------------------------------- /chap18/ServiceServerImpl.java: -------------------------------------------------------------------------------- 1 | package chap18; 2 | import java.rmi.*; 3 | import java.util.*; 4 | import java.rmi.server.*; 5 | 6 | 7 | public class ServiceServerImpl extends UnicastRemoteObject implements ServiceServer { 8 | 9 | HashMap serviceList; 10 | 11 | 12 | public ServiceServerImpl() throws RemoteException { 13 | // start and set up services 14 | setUpServices(); 15 | } 16 | 17 | private void setUpServices() { 18 | serviceList = new HashMap(); 19 | serviceList.put("Dice Rolling Service", new DiceService()); 20 | serviceList.put("Day of the Week Service", new DayOfTheWeekService()); 21 | serviceList.put("Visual Music Service", new MiniMusicService()); 22 | } 23 | 24 | public Object[] getServiceList() { 25 | System.out.println("in remote"); 26 | return serviceList.keySet().toArray(); 27 | 28 | } 29 | 30 | public Service getService(Object serviceKey) throws RemoteException { 31 | Service theService = (Service) serviceList.get(serviceKey); 32 | return theService; 33 | } 34 | 35 | 36 | public static void main (String[] args) { 37 | 38 | try { 39 | Naming.rebind("ServiceServer", new ServiceServerImpl()); 40 | } catch(Exception ex) { } 41 | System.out.println("Remote service is running"); 42 | } 43 | 44 | } --------------------------------------------------------------------------------