├── Java The Complete Reference Ninth Edition SourceCode ├── Analog.png ├── Digital.png ├── Lilies.jpg ├── clearBP.gif ├── resume.gif ├── setBP.gif ├── AboutIcon.gif ├── HourGlass.png ├── StopWatch.png ├── SunFlower.jpg ├── ConeFlowers.JPG ├── ReadMe.txt ├── ApdxA.lst ├── Chap2.lst ├── Chap37.lst ├── Chap4.lst ├── Chap22.lst ├── Chap38.lst ├── Chap24.lst ├── Chap31.lst ├── Chap34.lst ├── Chap23.lst ├── Chap6.lst ├── Chap3.lst ├── Chap10.lst ├── Chap16.lst ├── Chap30.lst ├── Chap17.lst ├── Chap29.lst ├── Chap5.lst ├── Chap11.lst ├── Chap9.lst ├── Chap13.lst └── Chap36.lst ├── SourceCodeJavaFile └── chapter2 │ ├── ForTest.java │ ├── Example.java │ ├── BlockTest.java │ ├── Example2.java │ └── IfSample.java └── README.md /Java The Complete Reference Ninth Edition SourceCode/Analog.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hloong/Java-The-Complete-Reference-Ninth-Edition-SourceCode/HEAD/Java The Complete Reference Ninth Edition SourceCode/Analog.png -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Digital.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hloong/Java-The-Complete-Reference-Ninth-Edition-SourceCode/HEAD/Java The Complete Reference Ninth Edition SourceCode/Digital.png -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Lilies.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hloong/Java-The-Complete-Reference-Ninth-Edition-SourceCode/HEAD/Java The Complete Reference Ninth Edition SourceCode/Lilies.jpg -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/clearBP.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hloong/Java-The-Complete-Reference-Ninth-Edition-SourceCode/HEAD/Java The Complete Reference Ninth Edition SourceCode/clearBP.gif -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/resume.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hloong/Java-The-Complete-Reference-Ninth-Edition-SourceCode/HEAD/Java The Complete Reference Ninth Edition SourceCode/resume.gif -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/setBP.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hloong/Java-The-Complete-Reference-Ninth-Edition-SourceCode/HEAD/Java The Complete Reference Ninth Edition SourceCode/setBP.gif -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/AboutIcon.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hloong/Java-The-Complete-Reference-Ninth-Edition-SourceCode/HEAD/Java The Complete Reference Ninth Edition SourceCode/AboutIcon.gif -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/HourGlass.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hloong/Java-The-Complete-Reference-Ninth-Edition-SourceCode/HEAD/Java The Complete Reference Ninth Edition SourceCode/HourGlass.png -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/StopWatch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hloong/Java-The-Complete-Reference-Ninth-Edition-SourceCode/HEAD/Java The Complete Reference Ninth Edition SourceCode/StopWatch.png -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/SunFlower.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hloong/Java-The-Complete-Reference-Ninth-Edition-SourceCode/HEAD/Java The Complete Reference Ninth Edition SourceCode/SunFlower.jpg -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/ConeFlowers.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hloong/Java-The-Complete-Reference-Ninth-Edition-SourceCode/HEAD/Java The Complete Reference Ninth Edition SourceCode/ConeFlowers.JPG -------------------------------------------------------------------------------- /SourceCodeJavaFile/chapter2/ForTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | Demonstrate the for loop. 3 | 4 | Call this file "ForTest.java". 5 | */ 6 | class ForTest { 7 | public static void main(String args[]) { 8 | int x; 9 | 10 | for(x = 0; x<10; x = x+1) 11 | System.out.println("This is x: " + x); 12 | } 13 | } -------------------------------------------------------------------------------- /SourceCodeJavaFile/chapter2/Example.java: -------------------------------------------------------------------------------- 1 | /* 2 | This is a simple Java program. 3 | Call this file "Example.java". 4 | */ 5 | class Example { 6 | // Your program begins with a call to main(). 7 | public static void main(String args[]) { 8 | System.out.println("This is a simple Java program."); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /SourceCodeJavaFile/chapter2/BlockTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | Demonstrate a block of code. 3 | 4 | Call this file "BlockTest.java" 5 | */ 6 | class BlockTest { 7 | public static void main(String args[]) { 8 | int x, y; 9 | 10 | y = 20; 11 | 12 | // the target of this loop is a block 13 | for(x = 0; x<10; x++) { 14 | System.out.println("This is x: " + x); 15 | System.out.println("This is y: " + y); 16 | y = y - 2; 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /SourceCodeJavaFile/chapter2/Example2.java: -------------------------------------------------------------------------------- 1 | /* 2 | Here is another short example. 3 | Call this file "Example2.java". 4 | */ 5 | class Example2 { 6 | public static void main(String args[]) { 7 | int num; // this declares a variable called num 8 | 9 | num = 100; // this assigns num the value 100 10 | 11 | System.out.println("This is num: " + num); 12 | 13 | num = num * 2; 14 | 15 | System.out.print("The value of num * 2 is "); 16 | System.out.println(num); 17 | } 18 | } -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/ReadMe.txt: -------------------------------------------------------------------------------- 1 | These files contain the code listings for 2 | 3 | Java: The Complete Reference, Ninth Edition 4 | 5 | The source code is organized into files by chapter. 6 | For example, the file Chap7.lst contains the 7 | programs shown in Chapter 7. 8 | 9 | Within each chapter file, the listings are stored 10 | in the same order as they appear in the book. 11 | Simply edit the appropriate file to extract the 12 | listing in which you are interested. 13 | -------------------------------------------------------------------------------- /SourceCodeJavaFile/chapter2/IfSample.java: -------------------------------------------------------------------------------- 1 | /* 2 | Demonstrate the if. 3 | 4 | Call this file "IfSample.java". 5 | */ 6 | class IfSample { 7 | public static void main(String args[]) { 8 | int x, y; 9 | 10 | x = 10; 11 | y = 20; 12 | 13 | if(x < y) System.out.println("x is less than y"); 14 | 15 | x = x * 2; 16 | if(x == y) System.out.println("x now equal to y"); 17 | 18 | x = x * 2; 19 | if(x > y) System.out.println("x now greater than y"); 20 | 21 | // this won't display anything 22 | if(x == y) System.out.println("you won't see this"); 23 | } 24 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | >Java-The-Complete-Reference-Ninth-Edition-SourceCode 3 | 4 | These files contain the code listings for 5 | 6 | Java: The Complete Reference, Ninth Edition 7 | 8 | The source code is organized into files by chapter. 9 | For example, the file Chap7.lst contains the 10 | programs shown in Chapter 7. 11 | 12 | Within each chapter file, the listings are stored 13 | in the same order as they appear in the book. 14 | Simply edit the appropriate file to extract the 15 | listing in which you are interested. 16 | 17 | >Tips: 18 | You can open the ".lst" files with Sublime Text 19 | 20 | >The java file in the folder SourceCodeJavaFile 21 | -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/ApdxA.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | /** 3 | * This class draws a bar chart. 4 | * @author Herbert Schildt 5 | * @version 3.2 6 | */ 7 | 8 | listing 2 9 | import java.io.*; 10 | 11 | /** 12 | * This class demonstrates documentation comments. 13 | * @author Herbert Schildt 14 | * @version 1.2 15 | */ 16 | public class SquareNum { 17 | /** 18 | * This method returns the square of num. 19 | * This is a multiline description. You can use 20 | * as many lines as you like. 21 | * @param num The value to be squared. 22 | * @return num squared. 23 | */ 24 | public double square(double num) { 25 | return num * num; 26 | } 27 | 28 | /** 29 | * This method inputs a number from the user. 30 | * @return The value input as a double. 31 | * @exception IOException On input error. 32 | * @see IOException 33 | */ 34 | public double getNumber() throws IOException { 35 | // create a BufferedReader using System.in 36 | InputStreamReader isr = new InputStreamReader(System.in); 37 | BufferedReader inData = new BufferedReader(isr); 38 | String str; 39 | 40 | str = inData.readLine(); 41 | return (new Double(str)).doubleValue(); 42 | } 43 | /** 44 | * This method demonstrates square(). 45 | * @param args Unused. 46 | * @exception IOException On input error. 47 | * @see IOException 48 | */ 49 | 50 | public static void main(String args[]) 51 | throws IOException 52 | { 53 | SquareNum ob = new SquareNum(); 54 | double val; 55 | 56 | System.out.println("Enter value to be squared: "); 57 | val = ob.getNumber(); 58 | val = ob.square(val); 59 | 60 | System.out.println("Squared value is " + val); 61 | } 62 | } 63 | 64 |  -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap2.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | /* 3 | This is a simple Java program. 4 | Call this file "Example.java". 5 | */ 6 | class Example { 7 | // Your program begins with a call to main(). 8 | public static void main(String args[]) { 9 | System.out.println("This is a simple Java program."); 10 | } 11 | } 12 | 13 | listing 2 14 | /* 15 | Here is another short example. 16 | Call this file "Example2.java". 17 | */ 18 | class Example2 { 19 | public static void main(String args[]) { 20 | int num; // this declares a variable called num 21 | 22 | num = 100; // this assigns num the value 100 23 | 24 | System.out.println("This is num: " + num); 25 | 26 | num = num * 2; 27 | 28 | System.out.print("The value of num * 2 is "); 29 | System.out.println(num); 30 | } 31 | } 32 | 33 | listing 3 34 | /* 35 | Demonstrate the if. 36 | 37 | Call this file "IfSample.java". 38 | */ 39 | class IfSample { 40 | public static void main(String args[]) { 41 | int x, y; 42 | 43 | x = 10; 44 | y = 20; 45 | 46 | if(x < y) System.out.println("x is less than y"); 47 | 48 | x = x * 2; 49 | if(x == y) System.out.println("x now equal to y"); 50 | 51 | x = x * 2; 52 | if(x > y) System.out.println("x now greater than y"); 53 | 54 | // this won't display anything 55 | if(x == y) System.out.println("you won't see this"); 56 | } 57 | } 58 | 59 | listing 4 60 | /* 61 | Demonstrate the for loop. 62 | 63 | Call this file "ForTest.java". 64 | */ 65 | class ForTest { 66 | public static void main(String args[]) { 67 | int x; 68 | 69 | for(x = 0; x<10; x = x+1) 70 | System.out.println("This is x: " + x); 71 | } 72 | } 73 | 74 | listing 5 75 | /* 76 | Demonstrate a block of code. 77 | 78 | Call this file "BlockTest.java" 79 | */ 80 | class BlockTest { 81 | public static void main(String args[]) { 82 | int x, y; 83 | 84 | y = 20; 85 | 86 | // the target of this loop is a block 87 | for(x = 0; x<10; x++) { 88 | System.out.println("This is x: " + x); 89 | System.out.println("This is y: " + y); 90 | y = y - 2; 91 | } 92 | } 93 | } 94 | 95 |  -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap37.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | // A simple Bean. 3 | import java.awt.*; 4 | import java.awt.event.*; 5 | import java.io.Serializable; 6 | 7 | public class Colors extends Canvas implements Serializable { 8 | transient private Color color; // not persistent 9 | private boolean rectangular; // is persistent 10 | 11 | public Colors() { 12 | addMouseListener(new MouseAdapter() { 13 | public void mousePressed(MouseEvent me) { 14 | change(); 15 | } 16 | }); 17 | rectangular = false; 18 | setSize(200, 100); 19 | change(); 20 | } 21 | 22 | public boolean getRectangular() { 23 | return rectangular; 24 | } 25 | 26 | public void setRectangular(boolean flag) { 27 | this.rectangular = flag; 28 | repaint(); 29 | } 30 | 31 | public void change() { 32 | color = randomColor(); 33 | repaint(); 34 | } 35 | 36 | private Color randomColor() { 37 | int r = (int)(255*Math.random()); 38 | int g = (int)(255*Math.random()); 39 | int b = (int)(255*Math.random()); 40 | return new Color(r, g, b); 41 | } 42 | 43 | public void paint(Graphics g) { 44 | Dimension d = getSize(); 45 | int h = d.height; 46 | int w = d.width; 47 | g.setColor(color); 48 | if(rectangular) { 49 | g.fillRect(0, 0, w-1, h-1); 50 | } 51 | else { 52 | g.fillOval(0, 0, w-1, h-1); 53 | } 54 | } 55 | } 56 | 57 | listing 2 58 | // A Bean information class. 59 | import java.beans.*; 60 | public class ColorsBeanInfo extends SimpleBeanInfo { 61 | public PropertyDescriptor[] getPropertyDescriptors() { 62 | try { 63 | PropertyDescriptor rectangular = new 64 | PropertyDescriptor("rectangular", Colors.class); 65 | PropertyDescriptor pd[] = {rectangular}; 66 | return pd; 67 | } 68 | catch(Exception e) { 69 | System.out.println("Exception caught. " + e); 70 | } 71 | return null; 72 | } 73 | } 74 | 75 | listing 3 76 | // Show properties and events. 77 | import java.awt.*; 78 | import java.beans.*; 79 | 80 | public class IntrospectorDemo { 81 | public static void main(String args[]) { 82 | try { 83 | Class c = Class.forName("Colors"); 84 | BeanInfo beanInfo = Introspector.getBeanInfo(c); 85 | 86 | System.out.println("Properties:"); 87 | PropertyDescriptor propertyDescriptor[] = 88 | beanInfo.getPropertyDescriptors(); 89 | for(int i = 0; i < propertyDescriptor.length; i++) { 90 | System.out.println("\t" + propertyDescriptor[i].getName()); 91 | } 92 | 93 | System.out.println("Events:"); 94 | EventSetDescriptor eventSetDescriptor[] = 95 | beanInfo.getEventSetDescriptors(); 96 | for(int i = 0; i < eventSetDescriptor.length; i++) { 97 | System.out.println("\t" + eventSetDescriptor[i].getName()); 98 | } 99 | } 100 | catch(Exception e) { 101 | System.out.println("Exception caught. " + e); 102 | } 103 | } 104 | } 105 | 106 |  -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap4.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | // Demonstrate the basic arithmetic operators. 3 | class BasicMath { 4 | public static void main(String args[]) { 5 | // arithmetic using integers 6 | System.out.println("Integer Arithmetic"); 7 | int a = 1 + 1; 8 | int b = a * 3; 9 | int c = b / 4; 10 | int d = c - a; 11 | int e = -d; 12 | System.out.println("a = " + a); 13 | System.out.println("b = " + b); 14 | System.out.println("c = " + c); 15 | System.out.println("d = " + d); 16 | System.out.println("e = " + e); 17 | 18 | // arithmetic using doubles 19 | System.out.println("\nFloating Point Arithmetic"); 20 | double da = 1 + 1; 21 | double db = da * 3; 22 | double dc = db / 4; 23 | double dd = dc - a; 24 | double de = -dd; 25 | System.out.println("da = " + da); 26 | System.out.println("db = " + db); 27 | System.out.println("dc = " + dc); 28 | System.out.println("dd = " + dd); 29 | System.out.println("de = " + de); 30 | } 31 | } 32 | 33 | listing 2 34 | // Demonstrate the % operator. 35 | class Modulus { 36 | public static void main(String args[]) { 37 | int x = 42; 38 | double y = 42.25; 39 | 40 | System.out.println("x mod 10 = " + x % 10); 41 | System.out.println("y mod 10 = " + y % 10); 42 | } 43 | } 44 | 45 | listing 3 46 | // Demonstrate several assignment operators. 47 | class OpEquals { 48 | public static void main(String args[]) { 49 | int a = 1; 50 | int b = 2; 51 | int c = 3; 52 | 53 | a += 5; 54 | b *= 4; 55 | c += a * b; 56 | c %= 6; 57 | System.out.println("a = " + a); 58 | System.out.println("b = " + b); 59 | System.out.println("c = " + c); 60 | } 61 | } 62 | 63 | listing 4 64 | // Demonstrate ++ and --. 65 | class IncDec { 66 | public static void main(String args[]) { 67 | int a = 1; 68 | int b = 2; 69 | int c; 70 | int d; 71 | 72 | c = ++b; 73 | d = a++; 74 | c++; 75 | System.out.println("a = " + a); 76 | System.out.println("b = " + b); 77 | System.out.println("c = " + c); 78 | System.out.println("d = " + d); 79 | } 80 | } 81 | 82 | listing 5 83 | // Demonstrate the bitwise logical operators. 84 | class BitLogic { 85 | public static void main(String args[]) { 86 | String binary[] = { 87 | "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", 88 | "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" 89 | }; 90 | int a = 3; // 0 + 2 + 1 or 0011 in binary 91 | int b = 6; // 4 + 2 + 0 or 0110 in binary 92 | int c = a | b; 93 | int d = a & b; 94 | int e = a ^ b; 95 | int f = (~a & b) | (a & ~b); 96 | int g = ~a & 0x0f; 97 | 98 | System.out.println(" a = " + binary[a]); 99 | System.out.println(" b = " + binary[b]); 100 | System.out.println(" a|b = " + binary[c]); 101 | System.out.println(" a&b = " + binary[d]); 102 | System.out.println(" a^b = " + binary[e]); 103 | System.out.println("~a&b|a&~b = " + binary[f]); 104 | System.out.println(" ~a = " + binary[g]); 105 | } 106 | } 107 | 108 | listing 6 109 | // Left shifting a byte value. 110 | class ByteShift { 111 | public static void main(String args[]) { 112 | byte a = 64, b; 113 | int i; 114 | 115 | i = a << 2; 116 | b = (byte) (a << 2); 117 | 118 | System.out.println("Original value of a: " + a); 119 | System.out.println("i and b: " + i + " " + b); 120 | } 121 | } 122 | 123 | listing 7 124 | // Left shifting as a quick way to multiply by 2. 125 | class MultByTwo { 126 | public static void main(String args[]) { 127 | int i; 128 | int num = 0xFFFFFFE; 129 | 130 | for(i=0; i<4; i++) { 131 | num = num << 1; 132 | System.out.println(num); 133 | } 134 | } 135 | } 136 | 137 | listing 8 138 | // Masking sign extension. 139 | class HexByte { 140 | static public void main(String args[]) { 141 | char hex[] = { 142 | '0', '1', '2', '3', '4', '5', '6', '7', 143 | '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' 144 | }; 145 | byte b = (byte) 0xf1; 146 | 147 | System.out.println("b = 0x" + hex[(b >> 4) & 0x0f] + hex[b & 0x0f]); 148 | } 149 | } 150 | 151 | listing 9 152 | // Unsigned shifting a byte value. 153 | class ByteUShift { 154 | static public void main(String args[]) { 155 | char hex[] = { 156 | '0', '1', '2', '3', '4', '5', '6', '7', 157 | '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' 158 | }; 159 | byte b = (byte) 0xf1; 160 | byte c = (byte) (b >> 4); 161 | byte d = (byte) (b >>> 4); 162 | byte e = (byte) ((b & 0xff) >> 4); 163 | 164 | System.out.println(" b = 0x" 165 | + hex[(b >> 4) & 0x0f] + hex[b & 0x0f]); 166 | System.out.println(" b >> 4 = 0x" 167 | + hex[(c >> 4) & 0x0f] + hex[c & 0x0f]); 168 | System.out.println(" b >>> 4 = 0x" 169 | + hex[(d >> 4) & 0x0f] + hex[d & 0x0f]); 170 | System.out.println("(b & 0xff) >> 4 = 0x" 171 | + hex[(e >> 4) & 0x0f] + hex[e & 0x0f]); 172 | } 173 | } 174 | 175 | listing 10 176 | class OpBitEquals { 177 | public static void main(String args[]) { 178 | int a = 1; 179 | int b = 2; 180 | int c = 3; 181 | 182 | a |= 4; 183 | b >>= 1; 184 | c <<= 1; 185 | a ^= c; 186 | System.out.println("a = " + a); 187 | System.out.println("b = " + b); 188 | System.out.println("c = " + c); 189 | } 190 | } 191 | 192 | listing 11 193 | // Demonstrate the boolean logical operators. 194 | class BoolLogic { 195 | public static void main(String args[]) { 196 | boolean a = true; 197 | boolean b = false; 198 | boolean c = a | b; 199 | boolean d = a & b; 200 | boolean e = a ^ b; 201 | boolean f = (!a & b) | (a & !b); 202 | boolean g = !a; 203 | 204 | System.out.println(" a = " + a); 205 | System.out.println(" b = " + b); 206 | System.out.println(" a|b = " + c); 207 | System.out.println(" a&b = " + d); 208 | System.out.println(" a^b = " + e); 209 | System.out.println("!a&b|a&!b = " + f); 210 | System.out.println(" !a = " + g); 211 | } 212 | } 213 | 214 | listing 12 215 | // Demonstrate ?. 216 | class Ternary { 217 | public static void main(String args[]) { 218 | int i, k; 219 | 220 | i = 10; 221 | k = i < 0 ? -i : i; // get absolute value of i 222 | System.out.print("Absolute value of "); 223 | System.out.println(i + " is " + k); 224 | 225 | i = -10; 226 | k = i < 0 ? -i : i; // get absolute value of i 227 | System.out.print("Absolute value of "); 228 | System.out.println(i + " is " + k); 229 | } 230 | } 231 |  -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap22.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | // Demonstrate InetAddress. 3 | import java.net.*; 4 | 5 | class InetAddressTest 6 | { 7 | public static void main(String args[]) throws UnknownHostException { 8 | InetAddress Address = InetAddress.getLocalHost(); 9 | System.out.println(Address); 10 | Address = InetAddress.getByName("www.HerbSchildt.com"); 11 | System.out.println(Address); 12 | InetAddress SW[] = InetAddress.getAllByName("www.nba.com"); 13 | for (int i=0; i> hdrMap = hpCon.getHeaderFields(); 153 | Set hdrField = hdrMap.keySet(); 154 | 155 | System.out.println("\nHere is the header:"); 156 | 157 | // Display all header keys and values.. 158 | for(String k : hdrField) { 159 | System.out.println("Key: " + k + 160 | " Value: " + hdrMap.get(k)); 161 | } 162 | } 163 | } 164 | 165 | listing 6 166 | // Demonstrate Datagrams. 167 | import java.net.*; 168 | 169 | class WriteServer { 170 | public static int serverPort = 998; 171 | public static int clientPort = 999; 172 | public static int buffer_size = 1024; 173 | public static DatagramSocket ds; 174 | public static byte buffer[] = new byte[buffer_size]; 175 | 176 | public static void TheServer() throws Exception { 177 | int pos=0; 178 | while (true) { 179 | int c = System.in.read(); 180 | switch (c) { 181 | case -1: 182 | System.out.println("Server Quits."); 183 | ds.close(); 184 | return; 185 | case '\r': 186 | break; 187 | case '\n': 188 | ds.send(new DatagramPacket(buffer,pos, 189 | InetAddress.getLocalHost(),clientPort)); 190 | pos=0; 191 | break; 192 | default: 193 | buffer[pos++] = (byte) c; 194 | } 195 | } 196 | } 197 | 198 | public static void TheClient() throws Exception { 199 | while(true) { 200 | DatagramPacket p = new DatagramPacket(buffer, buffer.length); 201 | ds.receive(p); 202 | System.out.println(new String(p.getData(), 0, p.getLength())); 203 | } 204 | } 205 | 206 | public static void main(String args[]) throws Exception { 207 | if(args.length == 1) { 208 | ds = new DatagramSocket(serverPort); 209 | TheServer(); 210 | } else { 211 | ds = new DatagramSocket(clientPort); 212 | TheClient(); 213 | } 214 | } 215 | } 216 | 217 | -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap38.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | import java.io.*; 3 | import javax.servlet.*; 4 | 5 | public class HelloServlet extends GenericServlet { 6 | 7 | public void service(ServletRequest request, 8 | ServletResponse response) 9 | throws ServletException, IOException { 10 | response.setContentType("text/html"); 11 | PrintWriter pw = response.getWriter(); 12 | pw.println("Hello!"); 13 | pw.close(); 14 | } 15 | } 16 | 17 | listing 2 18 | 19 | 20 |
21 |
24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 |
Employee
Phone
34 | 35 | 36 | 37 | 38 | listing 3 39 | import java.io.*; 40 | import java.util.*; 41 | import javax.servlet.*; 42 | 43 | public class PostParametersServlet 44 | extends GenericServlet { 45 | 46 | public void service(ServletRequest request, 47 | ServletResponse response) 48 | throws ServletException, IOException { 49 | 50 | // Get print writer. 51 | PrintWriter pw = response.getWriter(); 52 | 53 | // Get enumeration of parameter names. 54 | Enumeration e = request.getParameterNames(); 55 | 56 | // Display parameter names and values. 57 | while(e.hasMoreElements()) { 58 | String pname = (String)e.nextElement(); 59 | pw.print(pname + " = "); 60 | String pvalue = request.getParameter(pname); 61 | pw.println(pvalue); 62 | } 63 | pw.close(); 64 | } 65 | } 66 | 67 | listing 4 68 | 69 | 70 |
71 | 73 | Color: 74 | 79 |

80 | 81 | 82 | 83 | 84 | 85 | listing 5 86 | import java.io.*; 87 | import javax.servlet.*; 88 | import javax.servlet.http.*; 89 | 90 | public class ColorGetServlet extends HttpServlet { 91 | 92 | public void doGet(HttpServletRequest request, 93 | HttpServletResponse response) 94 | throws ServletException, IOException { 95 | 96 | String color = request.getParameter("color"); 97 | response.setContentType("text/html"); 98 | PrintWriter pw = response.getWriter(); 99 | pw.println("The selected color is: "); 100 | pw.println(color); 101 | pw.close(); 102 | } 103 | } 104 | 105 | listing 6 106 | 107 | 108 |
109 |
112 | Color: 113 | 118 |

119 | 120 |
121 | 122 | 123 | 124 | listing 7 125 | import java.io.*; 126 | import javax.servlet.*; 127 | import javax.servlet.http.*; 128 | 129 | public class ColorPostServlet extends HttpServlet { 130 | 131 | public void doPost(HttpServletRequest request, 132 | HttpServletResponse response) 133 | throws ServletException, IOException { 134 | 135 | String color = request.getParameter("color"); 136 | response.setContentType("text/html"); 137 | PrintWriter pw = response.getWriter(); 138 | pw.println("The selected color is: "); 139 | pw.println(color); 140 | pw.close(); 141 | } 142 | } 143 | 144 | listing 8 145 | 146 | 147 |
148 |
151 | Enter a value for MyCookie: 152 | 153 | 154 |
155 | 156 | 157 | 158 | listing 9 159 | import java.io.*; 160 | import javax.servlet.*; 161 | import javax.servlet.http.*; 162 | 163 | public class AddCookieServlet extends HttpServlet { 164 | 165 | public void doPost(HttpServletRequest request, 166 | HttpServletResponse response) 167 | throws ServletException, IOException { 168 | 169 | // Get parameter from HTTP request. 170 | String data = request.getParameter("data"); 171 | 172 | // Create cookie. 173 | Cookie cookie = new Cookie("MyCookie", data); 174 | 175 | // Add cookie to HTTP response. 176 | response.addCookie(cookie); 177 | 178 | // Write output to browser. 179 | response.setContentType("text/html"); 180 | PrintWriter pw = response.getWriter(); 181 | pw.println("MyCookie has been set to"); 182 | pw.println(data); 183 | pw.close(); 184 | } 185 | } 186 | 187 | listing 10 188 | import java.io.*; 189 | import javax.servlet.*; 190 | import javax.servlet.http.*; 191 | 192 | public class GetCookiesServlet extends HttpServlet { 193 | 194 | public void doGet(HttpServletRequest request, 195 | HttpServletResponse response) 196 | throws ServletException, IOException { 197 | 198 | // Get cookies from header of HTTP request. 199 | Cookie[] cookies = request.getCookies(); 200 | 201 | // Display these cookies. 202 | response.setContentType("text/html"); 203 | PrintWriter pw = response.getWriter(); 204 | pw.println(""); 205 | for(int i = 0; i < cookies.length; i++) { 206 | String name = cookies[i].getName(); 207 | String value = cookies[i].getValue(); 208 | pw.println("name = " + name + 209 | "; value = " + value); 210 | } 211 | pw.close(); 212 | } 213 | } 214 | 215 | listing 11 216 | import java.io.*; 217 | import java.util.*; 218 | import javax.servlet.*; 219 | import javax.servlet.http.*; 220 | 221 | public class DateServlet extends HttpServlet { 222 | 223 | public void doGet(HttpServletRequest request, 224 | HttpServletResponse response) 225 | throws ServletException, IOException { 226 | 227 | // Get the HttpSession object. 228 | HttpSession hs = request.getSession(true); 229 | 230 | // Get writer. 231 | response.setContentType("text/html"); 232 | PrintWriter pw = response.getWriter(); 233 | pw.print(""); 234 | 235 | // Display date/time of last access. 236 | Date date = (Date)hs.getAttribute("date"); 237 | if(date != null) { 238 | pw.print("Last access: " + date + "
"); 239 | } 240 | 241 | // Display current date/time. 242 | date = new Date(); 243 | hs.setAttribute("date", date); 244 | pw.println("Current date: " + date); 245 | } 246 | } 247 | 248 |  -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap24.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | // Demonstrate the mouse event handlers. 3 | import java.awt.*; 4 | import java.awt.event.*; 5 | import java.applet.*; 6 | /* 7 | 8 | 9 | */ 10 | 11 | public class MouseEvents extends Applet 12 | implements MouseListener, MouseMotionListener { 13 | 14 | String msg = ""; 15 | int mouseX = 0, mouseY = 0; // coordinates of mouse 16 | 17 | public void init() { 18 | addMouseListener(this); 19 | addMouseMotionListener(this); 20 | } 21 | 22 | // Handle mouse clicked. 23 | public void mouseClicked(MouseEvent me) { 24 | // save coordinates 25 | mouseX = 0; 26 | mouseY = 10; 27 | msg = "Mouse clicked."; 28 | repaint(); 29 | } 30 | 31 | // Handle mouse entered. 32 | public void mouseEntered(MouseEvent me) { 33 | // save coordinates 34 | mouseX = 0; 35 | mouseY = 10; 36 | msg = "Mouse entered."; 37 | repaint(); 38 | } 39 | 40 | // Handle mouse exited. 41 | public void mouseExited(MouseEvent me) { 42 | // save coordinates 43 | mouseX = 0; 44 | mouseY = 10; 45 | msg = "Mouse exited."; 46 | repaint(); 47 | } 48 | 49 | // Handle button pressed. 50 | public void mousePressed(MouseEvent me) { 51 | // save coordinates 52 | mouseX = me.getX(); 53 | mouseY = me.getY(); 54 | msg = "Down"; 55 | repaint(); 56 | } 57 | 58 | // Handle button released. 59 | public void mouseReleased(MouseEvent me) { 60 | // save coordinates 61 | mouseX = me.getX(); 62 | mouseY = me.getY(); 63 | msg = "Up"; 64 | repaint(); 65 | } 66 | 67 | // Handle mouse dragged. 68 | public void mouseDragged(MouseEvent me) { 69 | // save coordinates 70 | mouseX = me.getX(); 71 | mouseY = me.getY(); 72 | msg = "*"; 73 | showStatus("Dragging mouse at " + mouseX + ", " + mouseY); 74 | repaint(); 75 | } 76 | 77 | // Handle mouse moved. 78 | public void mouseMoved(MouseEvent me) { 79 | // show status 80 | showStatus("Moving mouse at " + me.getX() + ", " + me.getY()); 81 | } 82 | 83 | // Display msg in applet window at current X,Y location. 84 | public void paint(Graphics g) { 85 | g.drawString(msg, mouseX, mouseY); 86 | } 87 | } 88 | 89 | listing 2 90 | // Demonstrate the key event handlers. 91 | import java.awt.*; 92 | import java.awt.event.*; 93 | import java.applet.*; 94 | /* 95 | 96 | 97 | */ 98 | 99 | public class SimpleKey extends Applet 100 | implements KeyListener { 101 | 102 | String msg = ""; 103 | int X = 10, Y = 20; // output coordinates 104 | 105 | public void init() { 106 | addKeyListener(this); 107 | } 108 | 109 | public void keyPressed(KeyEvent ke) { 110 | showStatus("Key Down"); 111 | } 112 | 113 | public void keyReleased(KeyEvent ke) { 114 | showStatus("Key Up"); 115 | } 116 | 117 | public void keyTyped(KeyEvent ke) { 118 | msg += ke.getKeyChar(); 119 | repaint(); 120 | } 121 | 122 | // Display keystrokes. 123 | public void paint(Graphics g) { 124 | g.drawString(msg, X, Y); 125 | } 126 | } 127 | 128 | listing 3 129 | // Demonstrate some virutal key codes. 130 | import java.awt.*; 131 | import java.awt.event.*; 132 | import java.applet.*; 133 | /* 134 | 135 | 136 | */ 137 | 138 | public class KeyEvents extends Applet 139 | implements KeyListener { 140 | 141 | String msg = ""; 142 | int X = 10, Y = 20; // output coordinates 143 | 144 | public void init() { 145 | addKeyListener(this); 146 | } 147 | 148 | public void keyPressed(KeyEvent ke) { 149 | showStatus("Key Down"); 150 | 151 | int key = ke.getKeyCode(); 152 | switch(key) { 153 | case KeyEvent.VK_F1: 154 | msg += ""; 155 | break; 156 | case KeyEvent.VK_F2: 157 | msg += ""; 158 | break; 159 | case KeyEvent.VK_F3: 160 | msg += ""; 161 | break; 162 | case KeyEvent.VK_PAGE_DOWN: 163 | msg += ""; 164 | break; 165 | case KeyEvent.VK_PAGE_UP: 166 | msg += ""; 167 | break; 168 | case KeyEvent.VK_LEFT: 169 | msg += ""; 170 | break; 171 | case KeyEvent.VK_RIGHT: 172 | msg += ""; 173 | break; 174 | } 175 | 176 | repaint(); 177 | } 178 | 179 | public void keyReleased(KeyEvent ke) { 180 | showStatus("Key Up"); 181 | } 182 | 183 | public void keyTyped(KeyEvent ke) { 184 | msg += ke.getKeyChar(); 185 | repaint(); 186 | } 187 | 188 | // Display keystrokes. 189 | public void paint(Graphics g) { 190 | g.drawString(msg, X, Y); 191 | } 192 | } 193 | 194 | listing 4 195 | // Demonstrate an adaptor. 196 | import java.awt.*; 197 | import java.awt.event.*; 198 | import java.applet.*; 199 | /* 200 | 201 | 202 | */ 203 | 204 | public class AdapterDemo extends Applet { 205 | public void init() { 206 | addMouseListener(new MyMouseAdapter(this)); 207 | addMouseMotionListener(new MyMouseMotionAdapter(this)); 208 | } 209 | } 210 | 211 | class MyMouseAdapter extends MouseAdapter { 212 | AdapterDemo adapterDemo; 213 | public MyMouseAdapter(AdapterDemo adapterDemo) { 214 | this.adapterDemo = adapterDemo; 215 | } 216 | 217 | // Handle mouse clicked. 218 | public void mouseClicked(MouseEvent me) { 219 | adapterDemo.showStatus("Mouse clicked"); 220 | } 221 | } 222 | 223 | class MyMouseMotionAdapter extends MouseMotionAdapter { 224 | AdapterDemo adapterDemo; 225 | public MyMouseMotionAdapter(AdapterDemo adapterDemo) { 226 | this.adapterDemo = adapterDemo; 227 | } 228 | 229 | // Handle mouse dragged. 230 | public void mouseDragged(MouseEvent me) { 231 | adapterDemo.showStatus("Mouse dragged"); 232 | } 233 | } 234 | 235 | listing 5 236 | // This applet does NOT use an inner class. 237 | import java.applet.*; 238 | import java.awt.event.*; 239 | /* 240 | 241 | 242 | 243 | */ 244 | 245 | public class MousePressedDemo extends Applet { 246 | public void init() { 247 | addMouseListener(new MyMouseAdapter(this)); 248 | } 249 | } 250 | 251 | class MyMouseAdapter extends MouseAdapter { 252 | MousePressedDemo mousePressedDemo; 253 | public MyMouseAdapter(MousePressedDemo mousePressedDemo) { 254 | this.mousePressedDemo = mousePressedDemo; 255 | } 256 | public void mousePressed(MouseEvent me) { 257 | mousePressedDemo.showStatus("Mouse Pressed."); 258 | } 259 | } 260 | 261 | listing 6 262 | // Inner class demo 263 | import java.applet.*; 264 | import java.awt.event.*; 265 | /* 266 | 267 | 268 | 269 | */ 270 | 271 | public class InnerClassDemo extends Applet { 272 | public void init() { 273 | addMouseListener(new MyMouseAdapter()); 274 | } 275 | class MyMouseAdapter extends MouseAdapter { 276 | public void mousePressed(MouseEvent me) { 277 | showStatus("Mouse Pressed"); 278 | } 279 | } 280 | } 281 | 282 | listing 7 283 | // Anonymous inner class demo. 284 | import java.applet.*; 285 | import java.awt.event.*; 286 | /* 287 | 288 | 289 | */ 290 | 291 | public class AnonymousInnerClassDemo extends Applet { 292 | public void init() { 293 | addMouseListener(new MouseAdapter() { 294 | public void mousePressed(MouseEvent me) { 295 | showStatus("Mouse Pressed"); 296 | } 297 | }); 298 | } 299 | } 300 | 301 |  -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap31.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | // A simple Swing application. 3 | 4 | import javax.swing.*; 5 | 6 | class SwingDemo { 7 | 8 | SwingDemo() { 9 | 10 | // Create a new JFrame container. 11 | JFrame jfrm = new JFrame("A Simple Swing Application"); 12 | 13 | // Give the frame an initial size. 14 | jfrm.setSize(275, 100); 15 | 16 | // Terminate the program when the user closes the application. 17 | jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 | 19 | // Create a text-based label. 20 | JLabel jlab = new JLabel(" Swing means powerful GUIs."); 21 | 22 | // Add the label to the content pane. 23 | jfrm.add(jlab); 24 | 25 | // Display the frame. 26 | jfrm.setVisible(true); 27 | } 28 | 29 | public static void main(String args[]) { 30 | // Create the frame on the event dispatching thread. 31 | SwingUtilities.invokeLater(new Runnable() { 32 | public void run() { 33 | new SwingDemo(); 34 | } 35 | }); 36 | } 37 | } 38 | 39 | listing 2 40 | // Handle an event in a Swing program. 41 | 42 | import java.awt.*; 43 | import java.awt.event.*; 44 | import javax.swing.*; 45 | 46 | class EventDemo { 47 | 48 | JLabel jlab; 49 | 50 | EventDemo() { 51 | 52 | // Create a new JFrame container. 53 | JFrame jfrm = new JFrame("An Event Example"); 54 | 55 | // Specify FlowLayout for the layout manager. 56 | jfrm.setLayout(new FlowLayout()); 57 | 58 | // Give the frame an initial size. 59 | jfrm.setSize(220, 90); 60 | 61 | // Terminate the program when the user closes the application. 62 | jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 63 | 64 | // Make two buttons. 65 | JButton jbtnAlpha = new JButton("Alpha"); 66 | JButton jbtnBeta = new JButton("Beta"); 67 | 68 | // Add action listener for Alpha. 69 | jbtnAlpha.addActionListener(new ActionListener() { 70 | public void actionPerformed(ActionEvent ae) { 71 | jlab.setText("Alpha was pressed."); 72 | } 73 | }); 74 | 75 | // Add action listener for Beta. 76 | jbtnBeta.addActionListener(new ActionListener() { 77 | public void actionPerformed(ActionEvent ae) { 78 | jlab.setText("Beta was pressed."); 79 | } 80 | }); 81 | 82 | // Add the buttons to the content pane. 83 | jfrm.add(jbtnAlpha); 84 | jfrm.add(jbtnBeta); 85 | 86 | // Create a text-based label. 87 | jlab = new JLabel("Press a button."); 88 | 89 | // Add the label to the content pane. 90 | jfrm.add(jlab); 91 | 92 | // Display the frame. 93 | jfrm.setVisible(true); 94 | } 95 | 96 | public static void main(String args[]) { 97 | // Create the frame on the event dispatching thread. 98 | SwingUtilities.invokeLater(new Runnable() { 99 | public void run() { 100 | new EventDemo(); 101 | } 102 | }); 103 | } 104 | } 105 | 106 | listing 3 107 | // A simple Swing-based applet 108 | 109 | import javax.swing.*; 110 | import java.awt.*; 111 | import java.awt.event.*; 112 | 113 | /* 114 | This HTML can be used to launch the applet: 115 | 116 | 117 | 118 | */ 119 | 120 | public class MySwingApplet extends JApplet { 121 | JButton jbtnAlpha; 122 | JButton jbtnBeta; 123 | 124 | JLabel jlab; 125 | 126 | // Initialize the applet. 127 | public void init() { 128 | try { 129 | SwingUtilities.invokeAndWait(new Runnable () { 130 | public void run() { 131 | makeGUI(); // initialize the GUI 132 | } 133 | }); 134 | } catch(Exception exc) { 135 | System.out.println("Can't create because of "+ exc); 136 | } 137 | } 138 | 139 | // This applet does not need to override start(), stop(), 140 | // or destroy(). 141 | 142 | // Setup and initialize the GUI. 143 | private void makeGUI() { 144 | // Set the applet to use flow layout. 145 | setLayout(new FlowLayout()); 146 | 147 | // Make two buttons. 148 | jbtnAlpha = new JButton("Alpha"); 149 | jbtnBeta = new JButton("Beta"); 150 | 151 | // Add action listener for Alpha. 152 | jbtnAlpha.addActionListener(new ActionListener() { 153 | public void actionPerformed(ActionEvent le) { 154 | jlab.setText("Alpha was pressed."); 155 | } 156 | }); 157 | 158 | // Add action listener for Beta. 159 | jbtnBeta.addActionListener(new ActionListener() { 160 | public void actionPerformed(ActionEvent le) { 161 | jlab.setText("Beta was pressed."); 162 | } 163 | }); 164 | 165 | // Add the buttons to the content pane. 166 | add(jbtnAlpha); 167 | add(jbtnBeta); 168 | 169 | // Create a text-based label. 170 | jlab = new JLabel("Press a button."); 171 | 172 | // Add the label to the content pane. 173 | add(jlab); 174 | } 175 | } 176 | 177 | listing 3 178 | // Paint lines to a panel. 179 | 180 | import java.awt.*; 181 | import java.awt.event.*; 182 | import javax.swing.*; 183 | import java.util.*; 184 | 185 | // This class extends JPanel. It overrides 186 | // the paintComponent() method so that random 187 | // lines are plotted in the panel. 188 | class PaintPanel extends JPanel { 189 | Insets ins; // holds the panel's insets 190 | 191 | Random rand; // used to generate random numbers 192 | 193 | // Construct a panel. 194 | PaintPanel() { 195 | 196 | // Put a border around the panel. 197 | setBorder( 198 | BorderFactory.createLineBorder(Color.RED, 5)); 199 | 200 | rand = new Random(); 201 | } 202 | 203 | // Override the paintComponent() method. 204 | protected void paintComponent(Graphics g) { 205 | // Always call the superclass method first. 206 | super.paintComponent(g); 207 | 208 | int x, y, x2, y2; 209 | 210 | // Get the height and width of the component. 211 | int height = getHeight(); 212 | int width = getWidth(); 213 | 214 | // Get the insets. 215 | ins = getInsets(); 216 | 217 | // Draw ten lines whose endpoints are randomly generated. 218 | for(int i=0; i < 10; i++) { 219 | // Obtain random coordinates that define 220 | // the endpoints of each line. 221 | x = rand.nextInt(width-ins.left); 222 | y = rand.nextInt(height-ins.bottom); 223 | x2 = rand.nextInt(width-ins.left); 224 | y2 = rand.nextInt(height-ins.bottom); 225 | 226 | // Draw the line. 227 | g.drawLine(x, y, x2, y2); 228 | } 229 | } 230 | } 231 | 232 | // Demonstrate painting directly onto a panel. 233 | class PaintDemo { 234 | 235 | JLabel jlab; 236 | PaintPanel pp; 237 | 238 | PaintDemo() { 239 | 240 | // Create a new JFrame container. 241 | JFrame jfrm = new JFrame("Paint Demo"); 242 | 243 | // Give the frame an initial size. 244 | jfrm.setSize(200, 150); 245 | 246 | // Terminate the program when the user closes the application. 247 | jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 248 | 249 | // Create the panel that will be painted. 250 | pp = new PaintPanel(); 251 | 252 | // Add the panel to the content pane. Because the default 253 | // border layout is used, the panel will automatically be 254 | // sized to fit the center region. 255 | jfrm.add(pp); 256 | 257 | // Display the frame. 258 | jfrm.setVisible(true); 259 | } 260 | 261 | public static void main(String args[]) { 262 | // Create the frame on the event dispatching thread. 263 | SwingUtilities.invokeLater(new Runnable() { 264 | public void run() { 265 | new PaintDemo(); 266 | } 267 | }); 268 | } 269 | } 270 | 271 | -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap34.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | // A JavaFX application skeleton. 3 | 4 | import javafx.application.*; 5 | import javafx.scene.*; 6 | import javafx.stage.*; 7 | import javafx.scene.layout.*; 8 | 9 | public class JavaFXSkel extends Application { 10 | 11 | public static void main(String[] args) { 12 | 13 | System.out.println("Launching JavaFX application."); 14 | 15 | // Start the JavaFX application by calling launch(). 16 | launch(args); 17 | } 18 | 19 | // Override the init() method. 20 | public void init() { 21 | System.out.println("Inside the init() method."); 22 | } 23 | 24 | // Override the start() method. 25 | public void start(Stage myStage) { 26 | 27 | System.out.println("Inside the start() method."); 28 | 29 | // Give the stage a title. 30 | myStage.setTitle("JavaFX Skeleton."); 31 | 32 | // Create a root node. In this case, a flow layout pane 33 | // is used, but several alternatives exist. 34 | FlowPane rootNode = new FlowPane(); 35 | 36 | // Create a scene. 37 | Scene myScene = new Scene(rootNode, 300, 200); 38 | 39 | // Set the scene on the stage. 40 | myStage.setScene(myScene); 41 | 42 | // Show the stage and its scene. 43 | myStage.show(); 44 | 45 | } 46 | 47 | // Override the stop() method. 48 | public void stop() { 49 | System.out.println("Inside the stop() method."); 50 | } 51 | } 52 | 53 | listing 2 54 | // Demontrate a JavaFX label. 55 | 56 | import javafx.application.*; 57 | import javafx.scene.*; 58 | import javafx.stage.*; 59 | import javafx.scene.layout.*; 60 | import javafx.scene.control.*; 61 | 62 | public class JavaFXLabelDemo extends Application { 63 | 64 | public static void main(String[] args) { 65 | 66 | // Start the JavaFX application by calling launch(). 67 | launch(args); 68 | } 69 | 70 | // Override the start() method. 71 | public void start(Stage myStage) { 72 | 73 | // Give the stage a title. 74 | myStage.setTitle("Demonstrate a JavaFX label."); 75 | 76 | // Use a FlowPane for the root node. 77 | FlowPane rootNode = new FlowPane(); 78 | 79 | // Create a scene. 80 | Scene myScene = new Scene(rootNode, 300, 200); 81 | 82 | // Set the scene on the stage. 83 | myStage.setScene(myScene); 84 | 85 | // Create a label. 86 | Label myLabel = new Label("This is a JavaFX label"); 87 | 88 | // Add the label to the scene graph. 89 | rootNode.getChildren().add(myLabel); 90 | 91 | // Show the stage and its scene. 92 | myStage.show(); 93 | } 94 | } 95 | 96 | listing 3 97 | // Demonstrate JavaFX events and buttons. 98 | 99 | import javafx.application.*; 100 | import javafx.scene.*; 101 | import javafx.stage.*; 102 | import javafx.scene.layout.*; 103 | import javafx.scene.control.*; 104 | import javafx.event.*; 105 | import javafx.geometry.*; 106 | 107 | public class JavaFXEventDemo extends Application { 108 | 109 | Label response; 110 | 111 | public static void main(String[] args) { 112 | 113 | // Start the JavaFX application by calling launch(). 114 | launch(args); 115 | } 116 | 117 | // Override the start() method. 118 | public void start(Stage myStage) { 119 | 120 | // Give the stage a title. 121 | myStage.setTitle("Demonstrate JavaFX Buttons and Events."); 122 | 123 | // Use a FlowPane for the root node. In this case, 124 | // vertical and horizontal gaps of 10. 125 | FlowPane rootNode = new FlowPane(10, 10); 126 | 127 | // Center the controls in the scene. 128 | rootNode.setAlignment(Pos.CENTER); 129 | 130 | // Create a scene. 131 | Scene myScene = new Scene(rootNode, 300, 100); 132 | 133 | // Set the scene on the stage. 134 | myStage.setScene(myScene); 135 | 136 | // Create a label. 137 | response = new Label("Push a Button"); 138 | 139 | // Create two push buttons. 140 | Button btnAlpha = new Button("Alpha"); 141 | Button btnBeta = new Button("Beta"); 142 | 143 | // Handle the action events for the Alpha button. 144 | btnAlpha.setOnAction(new EventHandler() { 145 | public void handle(ActionEvent ae) { 146 | response.setText("Alpha was pressed."); 147 | } 148 | }); 149 | 150 | // Handle the action events for the Beta button. 151 | btnBeta.setOnAction(new EventHandler() { 152 | public void handle(ActionEvent ae) { 153 | response.setText("Beta was pressed."); 154 | } 155 | }); 156 | 157 | // Add the label and buttons to the scene graph. 158 | rootNode.getChildren().addAll(btnAlpha, btnBeta, response); 159 | 160 | // Show the stage and its scene. 161 | myStage.show(); 162 | } 163 | } 164 | 165 | listing 4 166 | btnAlpha.setOnAction( (ae) -> 167 | response.setText("Alpha was pressed.") 168 | ); 169 | 170 | listing 5 171 | // Demonstrate drawing. 172 | 173 | import javafx.application.*; 174 | import javafx.scene.*; 175 | import javafx.stage.*; 176 | import javafx.scene.layout.*; 177 | import javafx.scene.control.*; 178 | import javafx.event.*; 179 | import javafx.geometry.*; 180 | import javafx.scene.shape.*; 181 | import javafx.scene.canvas.*; 182 | import javafx.scene.paint.*; 183 | import javafx.scene.text.*; 184 | 185 | public class DirectDrawDemo extends Application { 186 | 187 | GraphicsContext gc; 188 | 189 | Color[] colors = { Color.RED, Color.BLUE, Color.GREEN, Color.BLACK }; 190 | int colorIdx = 0; 191 | 192 | public static void main(String[] args) { 193 | 194 | // Start the JavaFX application by calling launch(). 195 | launch(args); 196 | } 197 | 198 | // Override the start() method. 199 | public void start(Stage myStage) { 200 | 201 | // Give the stage a title. 202 | myStage.setTitle("Draw Directly to a Canvas."); 203 | 204 | // Use a FlowPane for the root node. 205 | FlowPane rootNode = new FlowPane(); 206 | 207 | // Center the nodes in the scene. 208 | rootNode.setAlignment(Pos.CENTER); 209 | 210 | // Create a scene. 211 | Scene myScene = new Scene(rootNode, 450, 450); 212 | 213 | // Set the scene on the stage. 214 | myStage.setScene(myScene); 215 | 216 | // Create a canvas. 217 | Canvas myCanvas = new Canvas(400, 400); 218 | 219 | // Get the graphics context for the canvas. 220 | gc = myCanvas.getGraphicsContext2D(); 221 | 222 | // Create a push button. 223 | Button btnChangeColor = new Button("Change Color"); 224 | 225 | // Handle the action events for the Change Color button. 226 | btnChangeColor.setOnAction(new EventHandler() { 227 | public void handle(ActionEvent ae) { 228 | 229 | // Set the stroke and fill color. 230 | gc.setStroke(colors[colorIdx]); 231 | gc.setFill(colors[colorIdx]); 232 | 233 | // Redraw the line, text, and filled rectangle in the 234 | // new color. This leaves the color of the other nodes 235 | // unchanged. 236 | gc.strokeLine(0, 0, 200, 200); 237 | gc.fillText("This is drawn on the canvas.", 60, 50); 238 | gc.fillRect(100, 320, 300, 40); 239 | 240 | // Change the color. 241 | colorIdx++; 242 | if(colorIdx == colors.length) colorIdx= 0; 243 | } 244 | }); 245 | 246 | // Draw initial output on the canvas. 247 | gc.strokeLine(0, 0, 200, 200); 248 | gc.strokeOval(100, 100, 200, 200); 249 | gc.strokeRect(0, 200, 50, 200); 250 | gc.fillOval(0, 0, 20, 20); 251 | gc.fillRect(100, 320, 300, 40); 252 | 253 | // Set the font size to 20 and draw text. 254 | gc.setFont(new Font(20)); 255 | gc.fillText("This is drawn on the canvas.", 60, 50); 256 | 257 | // Add the canvas and button to the scene graph. 258 | rootNode.getChildren().addAll(myCanvas, btnChangeColor); 259 | 260 | // Show the stage and its scene. 261 | myStage.show(); 262 | } 263 | } 264 | 265 | -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap23.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | // An Applet skeleton. 3 | import java.awt.*; 4 | import java.applet.*; 5 | /* 6 | 7 | 8 | */ 9 | 10 | public class AppletSkel extends Applet { 11 | // Called first. 12 | public void init() { 13 | // initialization 14 | } 15 | 16 | /* Called second, after init(). Also called whenever 17 | the applet is restarted. */ 18 | public void start() { 19 | // start or resume execution 20 | } 21 | 22 | // Called when the applet is stopped. 23 | public void stop() { 24 | // suspends execution 25 | } 26 | 27 | /* Called when applet is terminated. This is the last 28 | method executed. */ 29 | public void destroy() { 30 | // perform shutdown activities 31 | } 32 | 33 | // Called when an applet's window must be restored. 34 | public void paint(Graphics g) { 35 | // redisplay contents of window 36 | } 37 | } 38 | 39 | listing 2 40 | /* A simple applet that sets the foreground and 41 | background colors and outputs a string. */ 42 | import java.awt.*; 43 | import java.applet.*; 44 | /* 45 | 46 | 47 | */ 48 | 49 | public class Sample extends Applet{ 50 | String msg; 51 | 52 | // set the foreground and background colors. 53 | public void init() { 54 | setBackground(Color.cyan); 55 | setForeground(Color.red); 56 | msg = "Inside init( ) --"; 57 | } 58 | 59 | // Initialize the string to be displayed. 60 | public void start() { 61 | msg += " Inside start( ) --"; 62 | } 63 | 64 | // Display msg in applet window. 65 | public void paint(Graphics g) { 66 | msg += " Inside paint( )."; 67 | g.drawString(msg, 10, 30); 68 | } 69 | } 70 | 71 | listing 3 72 | /* A simple banner applet. 73 | 74 | This applet creates a thread that scrolls 75 | the message contained in msg right to left 76 | across the applet's window. 77 | */ 78 | import java.awt.*; 79 | import java.applet.*; 80 | /* 81 | 82 | 83 | */ 84 | 85 | public class SimpleBanner extends Applet implements Runnable { 86 | String msg = " A Simple Moving Banner."; 87 | Thread t = null; 88 | int state; 89 | boolean stopFlag; 90 | 91 | // Set colors and initialize thread. 92 | public void init() { 93 | setBackground(Color.cyan); 94 | setForeground(Color.red); 95 | } 96 | 97 | // Start thread 98 | public void start() { 99 | t = new Thread(this); 100 | stopFlag = false; 101 | t.start(); 102 | } 103 | 104 | // Entry point for the thread that runs the banner. 105 | public void run() { 106 | 107 | // Display banner 108 | for( ; ; ) { 109 | try { 110 | repaint(); 111 | Thread.sleep(250); 112 | if(stopFlag) 113 | break; 114 | } catch(InterruptedException e) {} 115 | } 116 | } 117 | 118 | // Pause the banner. 119 | public void stop() { 120 | stopFlag = true; 121 | t = null; 122 | } 123 | 124 | // Display the banner. 125 | public void paint(Graphics g) { 126 | char ch; 127 | 128 | ch = msg.charAt(0); 129 | msg = msg.substring(1, msg.length()); 130 | msg += ch; 131 | 132 | g.drawString(msg, 50, 30); 133 | } 134 | } 135 | 136 | listing 4 137 | // Using the Status Window. 138 | import java.awt.*; 139 | import java.applet.*; 140 | /* 141 | 142 | 143 | */ 144 | 145 | public class StatusWindow extends Applet{ 146 | public void init() { 147 | setBackground(Color.cyan); 148 | } 149 | 150 | // Display msg in applet window. 151 | public void paint(Graphics g) { 152 | g.drawString("This is in the applet window.", 10, 20); 153 | showStatus("This is shown in the status window."); 154 | } 155 | } 156 | 157 | listing 5 158 | // Use Parameters 159 | import java.awt.*; 160 | import java.applet.*; 161 | /* 162 | 163 | 164 | 165 | 166 | 167 | 168 | */ 169 | 170 | public class ParamDemo extends Applet{ 171 | String fontName; 172 | int fontSize; 173 | float leading; 174 | boolean active; 175 | 176 | // Initialize the string to be displayed. 177 | public void start() { 178 | String param; 179 | 180 | fontName = getParameter("fontName"); 181 | if(fontName == null) 182 | fontName = "Not Found"; 183 | 184 | param = getParameter("fontSize"); 185 | try { 186 | if(param != null) // if not found 187 | fontSize = Integer.parseInt(param); 188 | else 189 | fontSize = 0; 190 | } catch(NumberFormatException e) { 191 | fontSize = -1; 192 | } 193 | 194 | param = getParameter("leading"); 195 | try { 196 | if(param != null) // if not found 197 | leading = Float.valueOf(param).floatValue(); 198 | else 199 | leading = 0; 200 | } catch(NumberFormatException e) { 201 | leading = -1; 202 | } 203 | 204 | param = getParameter("accountEnabled"); 205 | if(param != null) 206 | active = Boolean.valueOf(param).booleanValue(); 207 | } 208 | 209 | // Display parameters. 210 | public void paint(Graphics g) { 211 | g.drawString("Font name: " + fontName, 0, 10); 212 | g.drawString("Font size: " + fontSize, 0, 26); 213 | g.drawString("Leading: " + leading, 0, 42); 214 | g.drawString("Account Active: " + active, 0, 58); 215 | } 216 | } 217 | 218 | listing 6 219 | // A parameterized banner 220 | import java.awt.*; 221 | import java.applet.*; 222 | /* 223 | 224 | 225 | 226 | */ 227 | 228 | public class ParamBanner extends Applet implements Runnable { 229 | String msg; 230 | Thread t = null; 231 | int state; 232 | boolean stopFlag; 233 | 234 | // Set colors and initialize thread. 235 | public void init() { 236 | setBackground(Color.cyan); 237 | setForeground(Color.red); 238 | } 239 | 240 | // Start thread 241 | public void start() { 242 | msg = getParameter("message"); 243 | if(msg == null) msg = "Message not found."; 244 | msg = " " + msg; 245 | t = new Thread(this); 246 | stopFlag = false; 247 | t.start(); 248 | } 249 | 250 | // Entry point for the thread that runs the banner. 251 | public void run() { 252 | 253 | // Display banner 254 | for( ; ; ) { 255 | try { 256 | repaint(); 257 | Thread.sleep(250); 258 | if(stopFlag) 259 | break; 260 | } catch(InterruptedException e) {} 261 | } 262 | } 263 | 264 | // Pause the banner. 265 | public void stop() { 266 | stopFlag = true; 267 | t = null; 268 | } 269 | 270 | // Display the banner. 271 | public void paint(Graphics g) { 272 | char ch; 273 | 274 | ch = msg.charAt(0); 275 | msg = msg.substring(1, msg.length()); 276 | msg += ch; 277 | 278 | g.drawString(msg, 50, 30); 279 | } 280 | } 281 | 282 | listing 7 283 | // Display code and document bases. 284 | import java.awt.*; 285 | import java.applet.*; 286 | import java.net.*; 287 | /* 288 | 289 | 290 | */ 291 | 292 | public class Bases extends Applet{ 293 | // Display code and document bases. 294 | public void paint(Graphics g) { 295 | String msg; 296 | 297 | URL url = getCodeBase(); // get code base 298 | msg = "Code base: " + url.toString(); 299 | g.drawString(msg, 10, 20); 300 | 301 | url = getDocumentBase(); // get document base 302 | msg = "Document base: " + url.toString(); 303 | g.drawString(msg, 10, 40); 304 | } 305 | } 306 | 307 | listing 8 308 | /* Using an applet context, getCodeBase(), 309 | and showDocument() to display an HTML file. 310 | */ 311 | 312 | import java.awt.*; 313 | import java.applet.*; 314 | import java.net.*; 315 | /* 316 | 317 | 318 | */ 319 | 320 | public class ACDemo extends Applet{ 321 | public void start() { 322 | AppletContext ac = getAppletContext(); 323 | URL url = getCodeBase(); // get url of this applet 324 | 325 | try { 326 | ac.showDocument(new URL(url+"Test.html")); 327 | } catch(MalformedURLException e) { 328 | showStatus("URL not found"); 329 | } 330 | } 331 | } 332 | -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap6.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | class Box { 3 | double width; 4 | double height; 5 | double depth; 6 | } 7 | 8 | listing 2 9 | /* A program that uses the Box class. 10 | 11 | Call this file BoxDemo.java 12 | */ 13 | class Box { 14 | double width; 15 | double height; 16 | double depth; 17 | } 18 | 19 | // This class declares an object of type Box. 20 | class BoxDemo { 21 | public static void main(String args[]) { 22 | Box mybox = new Box(); 23 | double vol; 24 | 25 | // assign values to mybox's instance variables 26 | mybox.width = 10; 27 | mybox.height = 20; 28 | mybox.depth = 15; 29 | 30 | // compute volume of box 31 | vol = mybox.width * mybox.height * mybox.depth; 32 | 33 | System.out.println("Volume is " + vol); 34 | } 35 | } 36 | 37 | listing 3 38 | // This program declares two Box objects. 39 | 40 | class Box { 41 | double width; 42 | double height; 43 | double depth; 44 | } 45 | 46 | class BoxDemo2 { 47 | public static void main(String args[]) { 48 | Box mybox1 = new Box(); 49 | Box mybox2 = new Box(); 50 | double vol; 51 | 52 | // assign values to mybox1's instance variables 53 | mybox1.width = 10; 54 | mybox1.height = 20; 55 | mybox1.depth = 15; 56 | 57 | /* assign different values to mybox2's 58 | instance variables */ 59 | mybox2.width = 3; 60 | mybox2.height = 6; 61 | mybox2.depth = 9; 62 | 63 | // compute volume of first box 64 | vol = mybox1.width * mybox1.height * mybox1.depth; 65 | System.out.println("Volume is " + vol); 66 | 67 | // compute volume of second box 68 | vol = mybox2.width * mybox2.height * mybox2.depth; 69 | System.out.println("Volume is " + vol); 70 | } 71 | } 72 | 73 | listing 4 74 | // This program includes a method inside the box class. 75 | 76 | class Box { 77 | double width; 78 | double height; 79 | double depth; 80 | 81 | // display volume of a box 82 | void volume() { 83 | System.out.print("Volume is "); 84 | System.out.println(width * height * depth); 85 | } 86 | } 87 | 88 | class BoxDemo3 { 89 | public static void main(String args[]) { 90 | Box mybox1 = new Box(); 91 | Box mybox2 = new Box(); 92 | 93 | // assign values to mybox1's instance variables 94 | mybox1.width = 10; 95 | mybox1.height = 20; 96 | mybox1.depth = 15; 97 | 98 | /* assign different values to mybox2's 99 | instance variables */ 100 | mybox2.width = 3; 101 | mybox2.height = 6; 102 | mybox2.depth = 9; 103 | 104 | // display volume of first box 105 | mybox1.volume(); 106 | 107 | // display volume of second box 108 | mybox2.volume(); 109 | } 110 | } 111 | 112 | listing 5 113 | // Now, volume() returns the volume of a box. 114 | 115 | class Box { 116 | double width; 117 | double height; 118 | double depth; 119 | 120 | // compute and return volume 121 | double volume() { 122 | return width * height * depth; 123 | } 124 | } 125 | 126 | class BoxDemo4 { 127 | public static void main(String args[]) { 128 | Box mybox1 = new Box(); 129 | Box mybox2 = new Box(); 130 | double vol; 131 | 132 | // assign values to mybox1's instance variables 133 | mybox1.width = 10; 134 | mybox1.height = 20; 135 | mybox1.depth = 15; 136 | 137 | /* assign different values to mybox2's 138 | instance variables */ 139 | mybox2.width = 3; 140 | mybox2.height = 6; 141 | mybox2.depth = 9; 142 | 143 | // get volume of first box 144 | vol = mybox1.volume(); 145 | System.out.println("Volume is " + vol); 146 | 147 | // get volume of second box 148 | vol = mybox2.volume(); 149 | System.out.println("Volume is " + vol); 150 | } 151 | } 152 | 153 | listing 6 154 | // This program uses a parameterized method. 155 | 156 | class Box { 157 | double width; 158 | double height; 159 | double depth; 160 | 161 | // compute and return volume 162 | double volume() { 163 | return width * height * depth; 164 | } 165 | 166 | // sets dimensions of box 167 | void setDim(double w, double h, double d) { 168 | width = w; 169 | height = h; 170 | depth = d; 171 | } 172 | } 173 | 174 | class BoxDemo5 { 175 | public static void main(String args[]) { 176 | Box mybox1 = new Box(); 177 | Box mybox2 = new Box(); 178 | double vol; 179 | 180 | // initialize each box 181 | mybox1.setDim(10, 20, 15); 182 | mybox2.setDim(3, 6, 9); 183 | 184 | // get volume of first box 185 | vol = mybox1.volume(); 186 | System.out.println("Volume is " + vol); 187 | 188 | // get volume of second box 189 | vol = mybox2.volume(); 190 | System.out.println("Volume is " + vol); 191 | } 192 | } 193 | 194 | listing 7 195 | /* Here, Box uses a constructor to initialize the 196 | dimensions of a box. 197 | */ 198 | class Box { 199 | double width; 200 | double height; 201 | double depth; 202 | 203 | // This is the constructor for Box. 204 | Box() { 205 | System.out.println("Constructing Box"); 206 | width = 10; 207 | height = 10; 208 | depth = 10; 209 | } 210 | 211 | // compute and return volume 212 | double volume() { 213 | return width * height * depth; 214 | } 215 | } 216 | 217 | class BoxDemo6 { 218 | public static void main(String args[]) { 219 | // declare, allocate, and initialize Box objects 220 | Box mybox1 = new Box(); 221 | Box mybox2 = new Box(); 222 | 223 | double vol; 224 | 225 | // get volume of first box 226 | vol = mybox1.volume(); 227 | System.out.println("Volume is " + vol); 228 | 229 | // get volume of second box 230 | vol = mybox2.volume(); 231 | System.out.println("Volume is " + vol); 232 | } 233 | } 234 | 235 | listing 8 236 | /* Here, Box uses a parameterized constructor to 237 | initialize the dimensions of a box. 238 | */ 239 | class Box { 240 | double width; 241 | double height; 242 | double depth; 243 | 244 | // This is the constructor for Box. 245 | Box(double w, double h, double d) { 246 | width = w; 247 | height = h; 248 | depth = d; 249 | } 250 | 251 | // compute and return volume 252 | double volume() { 253 | return width * height * depth; 254 | } 255 | } 256 | 257 | class BoxDemo7 { 258 | public static void main(String args[]) { 259 | // declare, allocate, and initialize Box objects 260 | Box mybox1 = new Box(10, 20, 15); 261 | Box mybox2 = new Box(3, 6, 9); 262 | 263 | double vol; 264 | 265 | // get volume of first box 266 | vol = mybox1.volume(); 267 | System.out.println("Volume is " + vol); 268 | 269 | // get volume of second box 270 | vol = mybox2.volume(); 271 | System.out.println("Volume is " + vol); 272 | } 273 | } 274 | 275 | listing 9 276 | // A redundant use of this. 277 | Box(double w, double h, double d) { 278 | this.width = w; 279 | this.height = h; 280 | this.depth = d; 281 | } 282 | 283 | listing 10 284 | // Use this to resolve name-space collisions. 285 | Box(double width, double height, double depth) { 286 | this.width = width; 287 | this.height = height; 288 | this.depth = depth; 289 | } 290 | 291 | listing 11 292 | // This class defines an integer stack that can hold 10 values. 293 | class Stack { 294 | int stck[] = new int[10]; 295 | int tos; 296 | 297 | // Initialize top-of-stack 298 | Stack() { 299 | tos = -1; 300 | } 301 | 302 | // Push an item onto the stack 303 | void push(int item) { 304 | if(tos==9) 305 | System.out.println("Stack is full."); 306 | else 307 | stck[++tos] = item; 308 | } 309 | 310 | // Pop an item from the stack 311 | int pop() { 312 | if(tos < 0) { 313 | System.out.println("Stack underflow."); 314 | return 0; 315 | } 316 | else 317 | return stck[tos--]; 318 | } 319 | } 320 | 321 | listing 12 322 | class TestStack { 323 | public static void main(String args[]) { 324 | Stack mystack1 = new Stack(); 325 | Stack mystack2 = new Stack(); 326 | 327 | // push some numbers onto the stack 328 | for(int i=0; i<10; i++) mystack1.push(i); 329 | for(int i=10; i<20; i++) mystack2.push(i); 330 | 331 | // pop those numbers off the stack 332 | System.out.println("Stack in mystack1:"); 333 | for(int i=0; i<10; i++) 334 | System.out.println(mystack1.pop()); 335 | 336 | System.out.println("Stack in mystack2:"); 337 | for(int i=0; i<10; i++) 338 | System.out.println(mystack2.pop()); 339 | } 340 | } 341 | 342 |  -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap3.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | // Compute distance light travels using long variables. 3 | class Light { 4 | public static void main(String args[]) { 5 | int lightspeed; 6 | long days; 7 | long seconds; 8 | long distance; 9 | 10 | // approximate speed of light in miles per second 11 | lightspeed = 186000; 12 | 13 | days = 1000; // specify number of days here 14 | 15 | seconds = days * 24 * 60 * 60; // convert to seconds 16 | 17 | distance = lightspeed * seconds; // compute distance 18 | 19 | System.out.print("In " + days); 20 | System.out.print(" days light will travel about "); 21 | System.out.println(distance + " miles."); 22 | } 23 | } 24 | 25 | listing 2 26 | // Compute the area of a circle. 27 | class Area { 28 | public static void main(String args[]) { 29 | double pi, r, a; 30 | 31 | r = 10.8; // radius of circle 32 | pi = 3.1416; // pi, approximately 33 | a = pi * r * r; // compute area 34 | 35 | System.out.println("Area of circle is " + a); 36 | } 37 | } 38 | 39 | listing 3 40 | // Demonstrate char data type. 41 | class CharDemo { 42 | public static void main(String args[]) { 43 | char ch1, ch2; 44 | 45 | ch1 = 88; // code for X 46 | ch2 = 'Y'; 47 | 48 | System.out.print("ch1 and ch2: "); 49 | System.out.println(ch1 + " " + ch2); 50 | } 51 | } 52 | 53 | 54 | listing 4 55 | // char variables behave like integers. 56 | class CharDemo2 { 57 | public static void main(String args[]) { 58 | char ch1; 59 | 60 | ch1 = 'X'; 61 | System.out.println("ch1 contains " + ch1); 62 | 63 | ch1++; // increment ch1 64 | System.out.println("ch1 is now " + ch1); 65 | } 66 | } 67 | 68 | listing 5 69 | // Demonstrate boolean values. 70 | class BoolTest { 71 | public static void main(String args[]) { 72 | boolean b; 73 | 74 | b = false; 75 | System.out.println("b is " + b); 76 | b = true; 77 | System.out.println("b is " + b); 78 | 79 | // a boolean value can control the if statement 80 | if(b) System.out.println("This is executed."); 81 | 82 | b = false; 83 | if(b) System.out.println("This is not executed."); 84 | 85 | // outcome of a relational operator is a boolean value 86 | System.out.println("10 > 9 is " + (10 > 9)); 87 | } 88 | } 89 | 90 | listing 6 91 | // Demonstrate dynamic initialization. 92 | class DynInit { 93 | public static void main(String args[]) { 94 | double a = 3.0, b = 4.0; 95 | 96 | // c is dynamically initialized 97 | double c = Math.sqrt(a * a + b * b); 98 | 99 | System.out.println("Hypotenuse is " + c); 100 | } 101 | } 102 | 103 | listing 7 104 | // Demonstrate block scope. 105 | class Scope { 106 | public static void main(String args[]) { 107 | int x; // known to all code within main 108 | 109 | x = 10; 110 | if(x == 10) { // start new scope 111 | int y = 20; // known only to this block 112 | 113 | // x and y both known here. 114 | System.out.println("x and y: " + x + " " + y); 115 | x = y * 2; 116 | } 117 | // y = 100; // Error! y not known here 118 | 119 | // x is still known here. 120 | System.out.println("x is " + x); 121 | } 122 | } 123 | 124 | listing 8 125 | // Demonstrate lifetime of a variable. 126 | class LifeTime { 127 | public static void main(String args[]) { 128 | int x; 129 | 130 | for(x = 0; x < 3; x++) { 131 | int y = -1; // y is initialized each time block is entered 132 | System.out.println("y iz: " + y); // this always prints -1 133 | y = 100; 134 | System.out.println("y is now: " + y); 135 | } 136 | } 137 | } 138 | 139 | listing 9 140 | // This program will not compile 141 | class ScopeErr { 142 | public static void main(String args[]) { 143 | int bar = 1; 144 | { // creates a new scope 145 | int bar = 2; // Compile time error -- bar already defined! 146 | } 147 | } 148 | } 149 | 150 | 151 | listing 10 152 | // Demonstrate casts. 153 | class Conversion { 154 | public static void main(String args[]) { 155 | byte b; 156 | int i = 257; 157 | double d = 323.142; 158 | 159 | System.out.println("\nConversion of int to byte."); 160 | b = (byte) i; 161 | System.out.println("i and b " + i + " " + b); 162 | 163 | System.out.println("\nConversion of double to int."); 164 | i = (int) d; 165 | System.out.println("d and i " + d + " " + i); 166 | 167 | System.out.println("\nConversion of double to byte."); 168 | b = (byte) d; 169 | System.out.println("d and b " + d + " " + b); 170 | } 171 | } 172 | 173 | listing 11 174 | class Promote { 175 | public static void main(String args[]) { 176 | byte b = 42; 177 | char c = 'a'; 178 | short s = 1024; 179 | int i = 50000; 180 | float f = 5.67f; 181 | double d = .1234; 182 | double result = (f * b) + (i / c) - (d * s); 183 | System.out.println((f * b) + " + " + (i / c) + " - " + (d * s)); 184 | System.out.println("result = " + result); 185 | } 186 | } 187 | 188 | listing 12 189 | // Demonstrate a one-dimensional array. 190 | class Array { 191 | public static void main(String args[]) { 192 | int month_days[]; 193 | month_days = new int[12]; 194 | month_days[0] = 31; 195 | month_days[1] = 28; 196 | month_days[2] = 31; 197 | month_days[3] = 30; 198 | month_days[4] = 31; 199 | month_days[5] = 30; 200 | month_days[6] = 31; 201 | month_days[7] = 31; 202 | month_days[8] = 30; 203 | month_days[9] = 31; 204 | month_days[10] = 30; 205 | month_days[11] = 31; 206 | System.out.println("April has " + month_days[3] + " days."); 207 | } 208 | } 209 | 210 | listing 13 211 | // An improvied version of the previous program. 212 | class AutoArray { 213 | public static void main(String args[]) { 214 | int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 215 | System.out.println("April has " + month_days[3] + " days."); 216 | } 217 | } 218 | 219 | listing 14 220 | // Average an array of values. 221 | class Average { 222 | public static void main(String args[]) { 223 | double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5}; 224 | double result = 0; 225 | int i; 226 | 227 | for(i=0; i<5; i++) 228 | result = result + nums[i]; 229 | 230 | System.out.println("Average is " + result / 5); 231 | } 232 | } 233 | 234 | listing 15 235 | // Demonstrate a two-dimensional array. 236 | class TwoDArray { 237 | public static void main(String args[]) { 238 | int twoD[][]= new int[4][5]; 239 | int i, j, k = 0; 240 | 241 | for(i=0; i<4; i++) 242 | for(j=0; j<5; j++) { 243 | twoD[i][j] = k; 244 | k++; 245 | } 246 | 247 | for(i=0; i<4; i++) { 248 | for(j=0; j<5; j++) 249 | System.out.print(twoD[i][j] + " "); 250 | System.out.println(); 251 | } 252 | } 253 | } 254 | 255 | 256 | listing 16 257 | // Manually allocate differing size second dimensions. 258 | class TwoDAgain { 259 | public static void main(String args[]) { 260 | int twoD[][] = new int[4][]; 261 | twoD[0] = new int[1]; 262 | twoD[1] = new int[2]; 263 | twoD[2] = new int[3]; 264 | twoD[3] = new int[4]; 265 | 266 | int i, j, k = 0; 267 | 268 | for(i=0; i<4; i++) 269 | for(j=0; j 10) 296 | throw new MyException(a); 297 | System.out.println("Normal exit"); 298 | } 299 | 300 | public static void main(String args[]) { 301 | try { 302 | compute(1); 303 | compute(20); 304 | } catch (MyException e) { 305 | System.out.println("Caught " + e); 306 | } 307 | } 308 | } 309 | 310 | listing 15 311 | // Demonstrate exception chaining. 312 | class ChainExcDemo { 313 | static void demoproc() { 314 | // create an exception 315 | NullPointerException e = 316 | new NullPointerException("top layer"); 317 | 318 | // add a cause 319 | e.initCause(new ArithmeticException("cause")); 320 | 321 | throw e; 322 | } 323 | 324 | public static void main(String args[]) { 325 | try { 326 | demoproc(); 327 | } catch(NullPointerException e) { 328 | // display top level exception 329 | System.out.println("Caught: " + e); 330 | 331 | // display cause exception 332 | System.out.println("Original cause: " + 333 | e.getCause()); 334 | } 335 | } 336 | } 337 | 338 | listing 16 339 | // Demonstrate JDK 7's multi-catch feature. 340 | class MultiCatch { 341 | public static void main(String args[]) { 342 | int a=10, b=0; 343 | int vals[] = { 1, 2, 3 }; 344 | 345 | try { 346 | int result = a / b; // generate an ArithmeticException 347 | 348 | // vals[10] = 19; // generate an ArrayIndexOutOfBoundsException 349 | 350 | // This catch clause catches both exceptions. 351 | } catch(ArithmeticException | ArrayIndexOutOfBoundsException e) { 352 | System.out.println("Exception caught: " + e); 353 | } 354 | 355 | System.out.println("After multi-catch."); 356 | } 357 | } 358 | 359 | -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap16.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | // Construct one String from another. 3 | class MakeString { 4 | public static void main(String args[]) { 5 | char c[] = {'J', 'a', 'v', 'a'}; 6 | String s1 = new String(c); 7 | String s2 = new String(s1); 8 | 9 | System.out.println(s1); 10 | System.out.println(s2); 11 | } 12 | } 13 | 14 | listing 2 15 | // Construct string from subset of char array. 16 | class SubStringCons { 17 | public static void main(String args[]) { 18 | byte ascii[] = {65, 66, 67, 68, 69, 70 }; 19 | 20 | String s1 = new String(ascii); 21 | System.out.println(s1); 22 | 23 | String s2 = new String(ascii, 2, 3); 24 | System.out.println(s2); 25 | } 26 | } 27 | 28 | listing 3 29 | // Using concatenation to prevent long lines. 30 | class ConCat { 31 | public static void main(String args[]) { 32 | String longStr = "This could have been " + 33 | "a very long line that would have " + 34 | "wrapped around. But string concatenation " + 35 | "prevents this."; 36 | 37 | System.out.println(longStr); 38 | } 39 | } 40 | 41 | listing 4 42 | // Override toString() for Box class. 43 | class Box { 44 | double width; 45 | double height; 46 | double depth; 47 | 48 | Box(double w, double h, double d) { 49 | width = w; 50 | height = h; 51 | depth = d; 52 | } 53 | 54 | public String toString() { 55 | return "Dimensions are " + width + " by " + 56 | depth + " by " + height + "."; 57 | } 58 | } 59 | 60 | class toStringDemo { 61 | public static void main(String args[]) { 62 | Box b = new Box(10, 12, 14); 63 | String s = "Box b: " + b; // concatenate Box object 64 | 65 | System.out.println(b); // convert Box to string 66 | System.out.println(s); 67 | } 68 | } 69 | 70 | listing 5 71 | class getCharsDemo { 72 | public static void main(String args[]) { 73 | String s = "This is a demo of the getChars method."; 74 | int start = 10; 75 | int end = 14; 76 | char buf[] = new char[end - start]; 77 | 78 | s.getChars(start, end, buf, 0); 79 | System.out.println(buf); 80 | } 81 | } 82 | 83 | listing 6 84 | // Demonstrate equals() and equalsIgnoreCase(). 85 | class equalsDemo { 86 | public static void main(String args[]) { 87 | String s1 = "Hello"; 88 | String s2 = "Hello"; 89 | String s3 = "Good-bye"; 90 | String s4 = "HELLO"; 91 | System.out.println(s1 + " equals " + s2 + " -> " + 92 | s1.equals(s2)); 93 | System.out.println(s1 + " equals " + s3 + " -> " + 94 | s1.equals(s3)); 95 | System.out.println(s1 + " equals " + s4 + " -> " + 96 | s1.equals(s4)); 97 | System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + 98 | s1.equalsIgnoreCase(s4)); 99 | } 100 | } 101 | 102 | listing 7 103 | // equals() vs == 104 | class EqualsNotEqualTo { 105 | public static void main(String args[]) { 106 | String s1 = "Hello"; 107 | String s2 = new String(s1); 108 | 109 | System.out.println(s1 + " equals " + s2 + " -> " + 110 | s1.equals(s2)); 111 | System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2)); 112 | } 113 | } 114 | 115 | listing 8 116 | // A bubble sort for Strings. 117 | class SortString { 118 | static String arr[] = { 119 | "Now", "is", "the", "time", "for", "all", "good", "men", 120 | "to", "come", "to", "the", "aid", "of", "their", "country" 121 | }; 122 | public static void main(String args[]) { 123 | for(int j = 0; j < arr.length; j++) { 124 | for(int i = j + 1; i < arr.length; i++) { 125 | if(arr[i].compareTo(arr[j]) < 0) { 126 | String t = arr[j]; 127 | arr[j] = arr[i]; 128 | arr[i] = t; 129 | } 130 | } 131 | System.out.println(arr[j]); 132 | } 133 | } 134 | } 135 | 136 | listing 9 137 | // Demonstrate indexOf() and lastIndexOf(). 138 | class indexOfDemo { 139 | public static void main(String args[]) { 140 | String s = "Now is the time for all good men " + 141 | "to come to the aid of their country."; 142 | 143 | System.out.println(s); 144 | System.out.println("indexOf(t) = " + 145 | s.indexOf('t')); 146 | System.out.println("lastIndexOf(t) = " + 147 | s.lastIndexOf('t')); 148 | System.out.println("indexOf(the) = " + 149 | s.indexOf("the")); 150 | System.out.println("lastIndexOf(the) = " + 151 | s.lastIndexOf("the")); 152 | System.out.println("indexOf(t, 10) = " + 153 | s.indexOf('t', 10)); 154 | System.out.println("lastIndexOf(t, 60) = " + 155 | s.lastIndexOf('t', 60)); 156 | System.out.println("indexOf(the, 10) = " + 157 | s.indexOf("the", 10)); 158 | System.out.println("lastIndexOf(the, 60) = " + 159 | s.lastIndexOf("the", 60)); 160 | } 161 | } 162 | 163 | listing 10 164 | // Substring replacement. 165 | class StringReplace { 166 | public static void main(String args[]) { 167 | String org = "This is a test. This is, too."; 168 | String search = "is"; 169 | String sub = "was"; 170 | String result = ""; 171 | int i; 172 | 173 | do { // replace all matching substrings 174 | System.out.println(org); 175 | i = org.indexOf(search); 176 | if(i != -1) { 177 | result = org.substring(0, i); 178 | result = result + sub; 179 | result = result + org.substring(i + search.length()); 180 | org = result; 181 | } 182 | } while(i != -1); 183 | 184 | } 185 | } 186 | 187 | listing 11 188 | // Using trim() to process commands. 189 | import java.io.*; 190 | 191 | class UseTrim { 192 | public static void main(String args[]) 193 | throws IOException 194 | { 195 | // create a BufferedReader using System.in 196 | BufferedReader br = new 197 | BufferedReader(new InputStreamReader(System.in)); 198 | String str; 199 | 200 | System.out.println("Enter 'stop' to quit."); 201 | System.out.println("Enter State: "); 202 | do { 203 | str = br.readLine(); 204 | str = str.trim(); // remove whitespace 205 | 206 | if(str.equals("Illinois")) 207 | System.out.println("Capital is Springfield."); 208 | else if(str.equals("Missouri")) 209 | System.out.println("Capital is Jefferson City."); 210 | else if(str.equals("California")) 211 | System.out.println("Capital is Sacramento."); 212 | else if(str.equals("Washington")) 213 | System.out.println("Capital is Olympia."); 214 | // ... 215 | } while(!str.equals("stop")); 216 | } 217 | } 218 | 219 | listing 12 220 | // Demonstrate toUpperCase() and toLowerCase(). 221 | 222 | class ChangeCase { 223 | public static void main(String args[]) 224 | { 225 | String s = "This is a test."; 226 | 227 | System.out.println("Original: " + s); 228 | 229 | String upper = s.toUpperCase(); 230 | String lower = s.toLowerCase(); 231 | 232 | System.out.println("Uppercase: " + upper); 233 | System.out.println("Lowercase: " + lower); 234 | } 235 | } 236 | 237 | listing 13 238 | // Demonstrate the join() method defined by String. 239 | class StringJoinDemo { 240 | public static void main(String args[]) { 241 | 242 | String result = String.join(" ", "Alpha", "Beta", "Gamma"); 243 | System.out.println(result); 244 | 245 | result = String.join(", ", "John", "ID#: 569", 246 | "E-mail: John@HerbSchildt.com"); 247 | System.out.println(result); 248 | } 249 | } 250 | 251 | listing 14 252 | // StringBuffer length vs. capacity. 253 | class StringBufferDemo { 254 | public static void main(String args[]) { 255 | StringBuffer sb = new StringBuffer("Hello"); 256 | 257 | System.out.println("buffer = " + sb); 258 | System.out.println("length = " + sb.length()); 259 | System.out.println("capacity = " + sb.capacity()); 260 | } 261 | } 262 | 263 | listing 15 264 | // Demonstrate charAt() and setCharAt(). 265 | class setCharAtDemo { 266 | public static void main(String args[]) { 267 | StringBuffer sb = new StringBuffer("Hello"); 268 | System.out.println("buffer before = " + sb); 269 | System.out.println("charAt(1) before = " + sb.charAt(1)); 270 | sb.setCharAt(1, 'i'); 271 | sb.setLength(2); 272 | System.out.println("buffer after = " + sb); 273 | System.out.println("charAt(1) after = " + sb.charAt(1)); 274 | } 275 | } 276 | 277 | listing 16 278 | // Demonstrate append(). 279 | class appendDemo { 280 | public static void main(String args[]) { 281 | String s; 282 | int a = 42; 283 | StringBuffer sb = new StringBuffer(40); 284 | 285 | s = sb.append("a = ").append(a).append("!").toString(); 286 | System.out.println(s); 287 | } 288 | } 289 | 290 | listing 17 291 | // Demonstrate insert(). 292 | class insertDemo { 293 | public static void main(String args[]) { 294 | StringBuffer sb = new StringBuffer("I Java!"); 295 | 296 | sb.insert(2, "like "); 297 | System.out.println(sb); 298 | } 299 | } 300 | 301 | listing 18 302 | // Using reverse() to reverse a StringBuffer. 303 | class ReverseDemo { 304 | public static void main(String args[]) { 305 | StringBuffer s = new StringBuffer("abcdef"); 306 | 307 | System.out.println(s); 308 | s.reverse(); 309 | System.out.println(s); 310 | } 311 | } 312 | 313 | listing 19 314 | // Demonstrate delete() and deleteCharAt() 315 | class deleteDemo { 316 | public static void main(String args[]) { 317 | StringBuffer sb = new StringBuffer("This is a test."); 318 | 319 | sb.delete(4, 7); 320 | System.out.println("After delete: " + sb); 321 | 322 | sb.deleteCharAt(0); 323 | System.out.println("After deleteCharAt: " + sb); 324 | } 325 | } 326 | 327 | listing 20 328 | // Demonstrate replace() 329 | class replaceDemo { 330 | public static void main(String args[]) { 331 | StringBuffer sb = new StringBuffer("This is a test."); 332 | 333 | sb.replace(5, 7, "was"); 334 | System.out.println("After replace: " + sb); 335 | } 336 | } 337 | 338 | listing 21 339 | // Demonstrate replace() 340 | class IndexOfDemo { 341 | public static void main(String args[]) { 342 | StringBuffer sb = new StringBuffer("one two one"); 343 | int i; 344 | 345 | i = sb.indexOf("one"); 346 | System.out.println("First index: " + i); 347 | 348 | i = sb.lastIndexOf("one"); 349 | System.out.println("Last index: " + i); 350 | } 351 | } 352 | -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap30.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | // A simple pattern matching demo. 3 | import java.util.regex.*; 4 | 5 | class RegExpr { 6 | public static void main(String args[]) { 7 | Pattern pat; 8 | Matcher mat; 9 | boolean found; 10 | 11 | pat = Pattern.compile("Java"); 12 | mat = pat.matcher("Java"); 13 | 14 | found = mat.matches(); // check for a match 15 | 16 | System.out.println("Testing Java against Java."); 17 | if(found) System.out.println("Matches"); 18 | else System.out.println("No Match"); 19 | 20 | System.out.println(); 21 | 22 | System.out.println("Testing Java against Java 8."); 23 | mat = pat.matcher("Java 8"); // create a new matcher 24 | 25 | found = mat.matches(); // check for a match 26 | 27 | if(found) System.out.println("Matches"); 28 | else System.out.println("No Match"); 29 | } 30 | } 31 | 32 | listing 2 33 | // Use find() to find a subsequence. 34 | import java.util.regex.*; 35 | 36 | class RegExpr2 { 37 | public static void main(String args[]) { 38 | Pattern pat = Pattern.compile("Java"); 39 | Matcher mat = pat.matcher("Java 8"); 40 | 41 | System.out.println("Looking for Java in Java 8."); 42 | 43 | if(mat.find()) System.out.println("subsequence found"); 44 | else System.out.println("No Match"); 45 | } 46 | } 47 | 48 | listing 3 49 | // Use find() to find multiple subsequences. 50 | import java.util.regex.*; 51 | 52 | class RegExpr3 { 53 | public static void main(String args[]) { 54 | Pattern pat = Pattern.compile("test"); 55 | Matcher mat = pat.matcher("test 1 2 3 test"); 56 | 57 | while(mat.find()) { 58 | System.out.println("test found at index " + 59 | mat.start()); 60 | } 61 | } 62 | } 63 | 64 | listing 4 65 | // Use a quantifier. 66 | import java.util.regex.*; 67 | 68 | class RegExpr4 { 69 | public static void main(String args[]) { 70 | Pattern pat = Pattern.compile("W+"); 71 | Matcher mat = pat.matcher("W WW WWW"); 72 | 73 | while(mat.find()) 74 | System.out.println("Match: " + mat.group()); 75 | } 76 | } 77 | 78 | listing 5 79 | // Use wildcard and quantifier. 80 | import java.util.regex.*; 81 | 82 | class RegExpr5 { 83 | public static void main(String args[]) { 84 | Pattern pat = Pattern.compile("e.+d"); 85 | Matcher mat = pat.matcher("extend cup end table"); 86 | 87 | while(mat.find()) 88 | System.out.println("Match: " + mat.group()); 89 | } 90 | } 91 | 92 | listing 6 93 | // Use the ? quantifier. 94 | import java.util.regex.*; 95 | 96 | class RegExpr6 { 97 | public static void main(String args[]) { 98 | // Use reluctant matching behavoir. 99 | Pattern pat = Pattern.compile("e.+?d"); 100 | Matcher mat = pat.matcher("extend cup end table"); 101 | 102 | while(mat.find()) 103 | System.out.println("Match: " + mat.group()); 104 | } 105 | } 106 | 107 | listing 7 108 | // Use a character class. 109 | import java.util.regex.*; 110 | 111 | class RegExpr7 { 112 | public static void main(String args[]) { 113 | // Match lowercase words. 114 | Pattern pat = Pattern.compile("[a-z]+"); 115 | Matcher mat = pat.matcher("this is a test."); 116 | 117 | while(mat.find()) 118 | System.out.println("Match: " + mat.group()); 119 | } 120 | } 121 | 122 | listing 8 123 | // Use replaceAll(). 124 | import java.util.regex.*; 125 | 126 | class RegExpr8 { 127 | public static void main(String args[]) { 128 | String str = "Jon Jonathan Frank Ken Todd"; 129 | 130 | Pattern pat = Pattern.compile("Jon.*? "); 131 | Matcher mat = pat.matcher(str); 132 | 133 | System.out.println("Original sequence: " + str); 134 | 135 | str = mat.replaceAll("Eric "); 136 | 137 | System.out.println("Modified sequence: " + str); 138 | 139 | } 140 | } 141 | 142 | listing 9 143 | // Use split(). 144 | import java.util.regex.*; 145 | 146 | class RegExpr9 { 147 | public static void main(String args[]) { 148 | 149 | // Match lowercase words. 150 | Pattern pat = Pattern.compile("[ ,.!]"); 151 | 152 | String strs[] = pat.split("one two,alpha9 12!done."); 153 | 154 | for(int i=0; i < strs.length; i++) 155 | System.out.println("Next token: " + strs[i]); 156 | 157 | } 158 | } 159 | 160 | listing 10 161 | // Demonstrate reflection. 162 | import java.lang.reflect.*; 163 | public class ReflectionDemo1 { 164 | public static void main(String args[]) { 165 | try { 166 | Class c = Class.forName("java.awt.Dimension"); 167 | System.out.println("Constructors:"); 168 | Constructor constructors[] = c.getConstructors(); 169 | for(int i = 0; i < constructors.length; i++) { 170 | System.out.println(" " + constructors[i]); 171 | } 172 | 173 | System.out.println("Fields:"); 174 | Field fields[] = c.getFields(); 175 | for(int i = 0; i < fields.length; i++) { 176 | System.out.println(" " + fields[i]); 177 | } 178 | 179 | System.out.println("Methods:"); 180 | Method methods[] = c.getMethods(); 181 | for(int i = 0; i < methods.length; i++) { 182 | System.out.println(" " + methods[i]); 183 | } 184 | } 185 | catch(Exception e) { 186 | System.out.println("Exception: " + e); 187 | } 188 | } 189 | } 190 | 191 | listing 11 192 | // Show public methods. 193 | import java.lang.reflect.*; 194 | public class ReflectionDemo2 { 195 | public static void main(String args[]) { 196 | try { 197 | A a = new A(); 198 | Class c = a.getClass(); 199 | System.out.println("Public Methods:"); 200 | Method methods[] = c.getDeclaredMethods(); 201 | for(int i = 0; i < methods.length; i++) { 202 | int modifiers = methods[i].getModifiers(); 203 | if(Modifier.isPublic(modifiers)) { 204 | System.out.println(" " + methods[i].getName()); 205 | } 206 | } 207 | } 208 | catch(Exception e) { 209 | System.out.println("Exception: " + e); 210 | } 211 | } 212 | } 213 | 214 | class A { 215 | public void a1() { 216 | } 217 | public void a2() { 218 | } 219 | protected void a3() { 220 | } 221 | private void a4() { 222 | } 223 | } 224 | 225 | listing 12 226 | import java.rmi.*; 227 | public interface AddServerIntf extends Remote { 228 | double add(double d1, double d2) throws RemoteException; 229 | } 230 | 231 | listing 13 232 | import java.rmi.*; 233 | import java.rmi.server.*; 234 | public class AddServerImpl extends UnicastRemoteObject 235 | implements AddServerIntf { 236 | 237 | public AddServerImpl() throws RemoteException { 238 | } 239 | public double add(double d1, double d2) throws RemoteException { 240 | return d1 + d2; 241 | } 242 | } 243 | 244 | listing 14 245 | import java.net.*; 246 | import java.rmi.*; 247 | public class AddServer { 248 | public static void main(String args[]) { 249 | try { 250 | AddServerImpl addServerImpl = new AddServerImpl(); 251 | Naming.rebind("AddServer", addServerImpl); 252 | } 253 | catch(Exception e) { 254 | System.out.println("Exception: " + e); 255 | } 256 | } 257 | } 258 | 259 | listing 15 260 | import java.rmi.*; 261 | public class AddClient { 262 | public static void main(String args[]) { 263 | try { 264 | String addServerURL = "rmi://" + args[0] + "/AddServer"; 265 | AddServerIntf addServerIntf = 266 | (AddServerIntf)Naming.lookup(addServerURL); 267 | System.out.println("The first number is: " + args[1]); 268 | double d1 = Double.valueOf(args[1]).doubleValue(); 269 | System.out.println("The second number is: " + args[2]); 270 | 271 | double d2 = Double.valueOf(args[2]).doubleValue(); 272 | System.out.println("The sum is: " + addServerIntf.add(d1, d2)); 273 | } 274 | catch(Exception e) { 275 | System.out.println("Exception: " + e); 276 | } 277 | } 278 | } 279 | 280 | listing 16 281 | // Demonstrate date formats. 282 | import java.text.*; 283 | import java.util.*; 284 | 285 | public class DateFormatDemo { 286 | public static void main(String args[]) { 287 | Date date = new Date(); 288 | DateFormat df; 289 | 290 | df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.JAPAN); 291 | System.out.println("Japan: " + df.format(date)); 292 | 293 | df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.KOREA); 294 | System.out.println("Korea: " + df.format(date)); 295 | 296 | df = DateFormat.getDateInstance(DateFormat.LONG, Locale.UK); 297 | System.out.println("United Kingdom: " + df.format(date)); 298 | 299 | df = DateFormat.getDateInstance(DateFormat.FULL, Locale.US); 300 | System.out.println("United States: " + df.format(date)); 301 | } 302 | } 303 | 304 | listing 17 305 | // Demonstrate time formats. 306 | import java.text.*; 307 | import java.util.*; 308 | public class TimeFormatDemo { 309 | public static void main(String args[]) { 310 | Date date = new Date(); 311 | DateFormat df; 312 | 313 | df = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.JAPAN); 314 | System.out.println("Japan: " + df.format(date)); 315 | 316 | df = DateFormat.getTimeInstance(DateFormat.LONG, Locale.UK); 317 | System.out.println("United Kingdom: " + df.format(date)); 318 | 319 | df = DateFormat.getTimeInstance(DateFormat.FULL, Locale.CANADA); 320 | System.out.println("Canada: " + df.format(date)); 321 | } 322 | } 323 | 324 | listing 18 325 | // Demonstrate SimpleDateFormat. 326 | import java.text.*; 327 | import java.util.*; 328 | 329 | public class SimpleDateFormatDemo { 330 | public static void main(String args[]) { 331 | Date date = new Date(); 332 | SimpleDateFormat sdf; 333 | sdf = new SimpleDateFormat("hh:mm:ss"); 334 | System.out.println(sdf.format(date)); 335 | sdf = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz"); 336 | System.out.println(sdf.format(date)); 337 | sdf = new SimpleDateFormat("E MMM dd yyyy"); 338 | System.out.println(sdf.format(date)); 339 | } 340 | } 341 | 342 | listing 19 343 | // A Simple example of LocalDate and LocalTime. 344 | import java.time.*; 345 | 346 | class DateTimeDemo { 347 | public static void main(String args[]) { 348 | 349 | LocalDate curDate = LocalDate.now(); 350 | System.out.println(curDate); 351 | 352 | LocalTime curTime = LocalTime.now(); 353 | System.out.println(curTime); 354 | } 355 | } 356 | 357 | listing 20 358 | // Demonstrate DateTimeFormatter. 359 | import java.time.*; 360 | import java.time.format.*; 361 | 362 | class DateTimeDemo2 { 363 | public static void main(String args[]) { 364 | 365 | LocalDate curDate = LocalDate.now(); 366 | System.out.println(curDate.format( 367 | DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL))); 368 | 369 | LocalTime curTime = LocalTime.now(); 370 | System.out.println(curTime.format( 371 | DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT))); 372 | } 373 | } 374 | 375 | listing 21 376 | // Create a custom date and time format. 377 | import java.time.*; 378 | import java.time.format.*; 379 | 380 | class DateTimeDemo3 { 381 | public static void main(String args[]) { 382 | 383 | LocalDateTime curDateTime = LocalDateTime.now(); 384 | System.out.println(curDateTime.format( 385 | DateTimeFormatter.ofPattern("MMMM d',' yyyy h':'mm a"))); 386 | } 387 | } 388 | 389 | listing 22 390 | // Parse a date and time. 391 | import java.time.*; 392 | import java.time.format.*; 393 | 394 | class DateTimeDemo4 { 395 | public static void main(String args[]) { 396 | 397 | // Obtain a LocalDateTime object by parsing a date and time string. 398 | LocalDateTime curDateTime = 399 | LocalDateTime.parse("June 21, 2014 12:01 AM", 400 | DateTimeFormatter.ofPattern("MMMM d',' yyyy hh':'mm a")); 401 | 402 | // Now, display the parsed date and time. 403 | System.out.println(curDateTime.format( 404 | DateTimeFormatter.ofPattern("MMMM d',' yyyy h':'mm a"))); 405 | } 406 | } 407 | 408 | -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap17.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | class DoubleDemo { 3 | public static void main(String args[]) { 4 | Double d1 = new Double(3.14159); 5 | Double d2 = new Double("314159E-5"); 6 | 7 | System.out.println(d1 + " = " + d2 + " -> " + d1.equals(d2)); 8 | } 9 | } 10 | 11 | listing 2 12 | // Demonstrate isInfinite() and isNaN(). 13 | class InfNaN { 14 | public static void main(String args[]) { 15 | Double d1 = new Double(1/0.); 16 | Double d2 = new Double(0/0.); 17 | 18 | System.out.println(d1 + ": " + d1.isInfinite() + ", " + d1.isNaN()); 19 | System.out.println(d2 + ": " + d2.isInfinite() + ", " + d2.isNaN()); 20 | } 21 | } 22 | 23 | listing 3 24 | /* This program sums a list of numbers entered 25 | by the user. It converts the string representation 26 | of each number into an int using parseInt(). 27 | */ 28 | 29 | import java.io.*; 30 | 31 | class ParseDemo { 32 | public static void main(String args[]) 33 | throws IOException 34 | { 35 | // create a BufferedReader using System.in 36 | BufferedReader br = new 37 | BufferedReader(new InputStreamReader(System.in)); 38 | String str; 39 | int i; 40 | int sum=0; 41 | 42 | System.out.println("Enter numbers, 0 to quit."); 43 | do { 44 | str = br.readLine(); 45 | try { 46 | i = Integer.parseInt(str); 47 | } catch(NumberFormatException e) { 48 | System.out.println("Invalid format"); 49 | i = 0; 50 | } 51 | sum += i; 52 | System.out.println("Current sum is: " + sum); 53 | } while(i != 0); 54 | } 55 | } 56 | 57 | listing 4 58 | /* Convert an integer into binary, hexadecimal, 59 | and octal. 60 | */ 61 | 62 | class StringConversions { 63 | public static void main(String args[]) { 64 | int num = 19648; 65 | 66 | System.out.println(num + " in binary: " + 67 | Integer.toBinaryString(num)); 68 | 69 | System.out.println(num + " in octal: " + 70 | Integer.toOctalString(num)); 71 | 72 | System.out.println(num + " in hexadecimal: " + 73 | Integer.toHexString(num)); 74 | } 75 | } 76 | 77 | listing 5 78 | // Demonstrate several Is... methods. 79 | 80 | class IsDemo { 81 | public static void main(String args[]) { 82 | char a[] = {'a', 'b', '5', '?', 'A', ' '}; 83 | 84 | for(int i=0; i clObj; 317 | 318 | clObj = x.getClass(); // get Class reference 319 | System.out.println("x is object of type: " + 320 | clObj.getName()); 321 | 322 | clObj = y.getClass(); // get Class reference 323 | System.out.println("y is object of type: " + 324 | clObj.getName()); 325 | clObj = clObj.getSuperclass(); 326 | System.out.println("y's superclass is " + 327 | clObj.getName()); 328 | } 329 | } 330 | 331 | listing 16 332 | // Demonstrate toDegrees() and toRadians(). 333 | class Angles { 334 | public static void main(String args[]) { 335 | double theta = 120.0; 336 | 337 | System.out.println(theta + " degrees is " + 338 | Math.toRadians(theta) + " radians."); 339 | 340 | theta = 1.312; 341 | System.out.println(theta + " radians is " + 342 | Math.toDegrees(theta) + " degrees."); 343 | } 344 | } 345 | 346 | listing 17 347 | // Demonstrate thread groups. 348 | class NewThread extends Thread { 349 | boolean suspendFlag; 350 | 351 | NewThread(String threadname, ThreadGroup tgOb) { 352 | super(tgOb, threadname); 353 | System.out.println("New thread: " + this); 354 | suspendFlag = false; 355 | start(); // Start the thread 356 | } 357 | 358 | // This is the entry point for thread. 359 | public void run() { 360 | try { 361 | for(int i = 5; i > 0; i--) { 362 | System.out.println(getName() + ": " + i); 363 | Thread.sleep(1000); 364 | synchronized(this) { 365 | while(suspendFlag) { 366 | wait(); 367 | } 368 | } 369 | } 370 | } catch (Exception e) { 371 | System.out.println("Exception in " + getName()); 372 | } 373 | System.out.println(getName() + " exiting."); 374 | } 375 | 376 | synchronized void mysuspend() { 377 | suspendFlag = true; 378 | } 379 | 380 | synchronized void myresume() { 381 | suspendFlag = false; 382 | notify(); 383 | } 384 | } 385 | 386 | class ThreadGroupDemo { 387 | public static void main(String args[]) { 388 | ThreadGroup groupA = new ThreadGroup("Group A"); 389 | ThreadGroup groupB = new ThreadGroup("Group B"); 390 | 391 | NewThread ob1 = new NewThread("One", groupA); 392 | NewThread ob2 = new NewThread("Two", groupA); 393 | NewThread ob3 = new NewThread("Three", groupB); 394 | NewThread ob4 = new NewThread("Four", groupB); 395 | 396 | System.out.println("\nHere is output from list():"); 397 | groupA.list(); 398 | groupB.list(); 399 | System.out.println(); 400 | 401 | System.out.println("Suspending Group A"); 402 | Thread tga[] = new Thread[groupA.activeCount()]; 403 | groupA.enumerate(tga); // get threads in group 404 | for(int i = 0; i < tga.length; i++) { 405 | ((NewThread)tga[i]).mysuspend(); // suspend each thread 406 | } 407 | 408 | try { 409 | Thread.sleep(4000); 410 | } catch (InterruptedException e) { 411 | System.out.println("Main thread interrupted."); 412 | } 413 | 414 | System.out.println("Resuming Group A"); 415 | for(int i = 0; i < tga.length; i++) { 416 | ((NewThread)tga[i]).myresume(); // resume threads in group 417 | } 418 | 419 | // wait for threads to finish 420 | try { 421 | System.out.println("Waiting for threads to finish."); 422 | ob1.join(); 423 | ob2.join(); 424 | ob3.join(); 425 | ob4.join(); 426 | } catch (Exception e) { 427 | System.out.println("Exception in Main thread"); 428 | } 429 | 430 | System.out.println("Main thread exiting."); 431 | } 432 | } 433 | 434 | listing 18 435 | // Demonstrate Package 436 | class PkgTest { 437 | public static void main(String args[]) { 438 | Package pkgs[]; 439 | 440 | pkgs = Package.getPackages(); 441 | 442 | for(int i=0; i < pkgs.length; i++) 443 | System.out.println( 444 | pkgs[i].getName() + " " + 445 | pkgs[i].getImplementationTitle() + " " + 446 | pkgs[i].getImplementationVendor() + " " + 447 | pkgs[i].getImplementationVersion() 448 | ); 449 | 450 | } 451 | } 452 | 453 |  -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap29.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | // Demonstrate several Stream operations. 3 | 4 | import java.util.*; 5 | import java.util.stream.*; 6 | 7 | class StreamDemo { 8 | 9 | public static void main(String[] args) { 10 | 11 | // Create a list of Integer values. 12 | ArrayList myList = new ArrayList<>( ); 13 | myList.add(7); 14 | myList.add(18); 15 | myList.add(10); 16 | myList.add(24); 17 | myList.add(17); 18 | myList.add(5); 19 | 20 | System.out.println("Original list: " + myList); 21 | 22 | // Obtain a Stream to the array list. 23 | Stream myStream = myList.stream(); 24 | 25 | // Obtain the minimum and maximum value by uses of min(), 26 | // max(), isPresent(), and get(). 27 | Optional minVal = myStream.min(Integer::compare); 28 | if(minVal.isPresent()) System.out.println("Minimum value: " + 29 | minVal.get()); 30 | 31 | // Must obtain a new stream because previous call to min() 32 | // is a terminal operation that consumed the stream. 33 | myStream = myList.stream(); 34 | Optional maxVal = myStream.max(Integer::compare); 35 | if(maxVal.isPresent()) System.out.println("Maximum value: " + 36 | maxVal.get()); 37 | 38 | // Sort the stream by use of sorted(). 39 | Stream sortedStream = myList.stream().sorted(); 40 | 41 | // Display the sorted stream by use of forEach(). 42 | System.out.print("Sorted stream: "); 43 | sortedStream.forEach((n) -> System.out.print(n + " ")); 44 | System.out.println(); 45 | 46 | // Display only the odd values by use of filter(). 47 | Stream oddVals = 48 | myList.stream().sorted().filter((n) -> (n % 2) == 1); 49 | System.out.print("Odd values: "); 50 | oddVals.forEach((n) -> System.out.print(n + " ")); 51 | System.out.println(); 52 | 53 | // Display only the odd values that are greater than 5. Notice that 54 | // two filter operations are pipelined. 55 | oddVals = myList.stream().filter( (n) -> (n % 2) == 1) 56 | .filter((n) -> n > 5); 57 | System.out.print("Odd values greater than 5: "); 58 | oddVals.forEach((n) -> System.out.print(n + " ") ); 59 | System.out.println(); 60 | } 61 | } 62 | 63 | listing 2 64 | // Demonstrate the reduce() method. 65 | 66 | import java.util.*; 67 | import java.util.stream.*; 68 | 69 | class StreamDemo2 { 70 | 71 | public static void main(String[] args) { 72 | 73 | // Create a list of Integer values. 74 | ArrayList myList = new ArrayList<>( ); 75 | 76 | myList.add(7); 77 | myList.add(18); 78 | myList.add(10); 79 | myList.add(24); 80 | myList.add(17); 81 | myList.add(5); 82 | 83 | // Two ways to obtain the integer product of the elements 84 | // in myList by use of reduce(). 85 | Optional productObj = myList.stream().reduce((a,b) -> a*b); 86 | if(productObj.isPresent()) 87 | System.out.println("Product as Optional: " + productObj.get()); 88 | 89 | int product = myList.stream().reduce(1, (a,b) -> a*b); 90 | System.out.println("Product as int: " + product); 91 | } 92 | } 93 | 94 | listing 3 95 | // Demonstrate the use of a combiner with reduce() 96 | 97 | import java.util.*; 98 | import java.util.stream.*; 99 | 100 | class StreamDemo3 { 101 | 102 | public static void main(String[] args) { 103 | 104 | // This is now a list of double values. 105 | ArrayList myList = new ArrayList<>( ); 106 | 107 | myList.add(7.0); 108 | myList.add(18.0); 109 | myList.add(10.0); 110 | myList.add(24.0); 111 | myList.add(17.0); 112 | myList.add(5.0); 113 | 114 | double productOfSqrRoots = myList.parallelStream().reduce( 115 | 1.0, 116 | (a,b) -> a * Math.sqrt(b), 117 | (a,b) -> a * b 118 | ); 119 | 120 | System.out.println("Product of square roots: " + productOfSqrRoots); 121 | } 122 | } 123 | 124 | listing 4 125 | // Map one stream to another. 126 | 127 | import java.util.*; 128 | import java.util.stream.*; 129 | 130 | class StreamDemo4 { 131 | 132 | public static void main(String[] args) { 133 | 134 | // A list of double values. 135 | ArrayList myList = new ArrayList<>( ); 136 | 137 | myList.add(7.0); 138 | myList.add(18.0); 139 | myList.add(10.0); 140 | myList.add(24.0); 141 | myList.add(17.0); 142 | myList.add(5.0); 143 | 144 | // Map the square root of the elements in myList to a new stream. 145 | Stream sqrtRootStrm = myList.stream().map((a) -> Math.sqrt(a)); 146 | 147 | // Find the product to the square roots. 148 | double productOfSqrRoots = sqrtRootStrm.reduce(1.0, (a,b) -> a*b); 149 | 150 | System.out.println("Product of square roots is " + productOfSqrRoots); 151 | } 152 | } 153 | 154 | listing 5 155 | // Use map() to create a new stream that contains only 156 | // selected aspects of the original stream. 157 | 158 | import java.util.*; 159 | import java.util.stream.*; 160 | 161 | class NamePhoneEmail { 162 | String name; 163 | String phonenum; 164 | String email; 165 | 166 | NamePhoneEmail(String n, String p, String e) { 167 | name = n; 168 | phonenum = p; 169 | email = e; 170 | } 171 | } 172 | 173 | class NamePhone { 174 | String name; 175 | String phonenum; 176 | 177 | NamePhone(String n, String p) { 178 | name = n; 179 | phonenum = p; 180 | } 181 | } 182 | 183 | class StreamDemo5 { 184 | 185 | public static void main(String[] args) { 186 | 187 | // A list of names, phone numbers, and e-mail addresses. 188 | ArrayList myList = new ArrayList<>( ); 189 | 190 | myList.add(new NamePhoneEmail("Larry", "555-5555", 191 | "Larry@HerbSchildt.com")); 192 | myList.add(new NamePhoneEmail("James", "555-4444", 193 | "James@HerbSchildt.com")); 194 | myList.add(new NamePhoneEmail("Mary", "555-3333", 195 | "Mary@HerbSchildt.com")); 196 | 197 | System.out.println("Original values in myList: "); 198 | myList.stream().forEach( (a) -> { 199 | System.out.println(a.name + " " + a.phonenum + " " + a.email); 200 | }); 201 | System.out.println(); 202 | 203 | // Map just the names and phone numbers to a new stream. 204 | Stream nameAndPhone = myList.stream().map( 205 | (a) -> new NamePhone(a.name,a.phonenum) 206 | ); 207 | 208 | System.out.println("List of names and phone numbers: "); 209 | nameAndPhone.forEach( (a) -> { 210 | System.out.println(a.name + " " + a.phonenum); 211 | }); 212 | } 213 | } 214 | 215 | listing 6 216 | // Map a Stream to an intStream. 217 | 218 | import java.util.*; 219 | import java.util.stream.*; 220 | 221 | class StreamDemo6 { 222 | 223 | public static void main(String[] args) { 224 | 225 | // A list of double values. 226 | ArrayList myList = new ArrayList<>( ); 227 | 228 | myList.add(1.1); 229 | myList.add(3.6); 230 | myList.add(9.2); 231 | myList.add(4.7); 232 | myList.add(12.1); 233 | myList.add(5.0); 234 | 235 | System.out.print("Original values in myList: "); 236 | myList.stream().forEach( (a) -> { 237 | System.out.print(a + " "); 238 | }); 239 | System.out.println(); 240 | 241 | // Map the ceiling of the elements in myList to an InStream. 242 | IntStream cStrm = myList.stream().mapToInt((a) -> (int) Math.ceil(a)); 243 | 244 | System.out.print("The ceilings of the values in myList: "); 245 | cStrm.forEach( (a) -> { 246 | System.out.print(a + " "); 247 | }); 248 | 249 | } 250 | } 251 | 252 | listing 7 253 | // Use collect() to create a List and a Set from a stream. 254 | 255 | import java.util.*; 256 | import java.util.stream.*; 257 | 258 | class NamePhoneEmail { 259 | String name; 260 | String phonenum; 261 | String email; 262 | 263 | NamePhoneEmail(String n, String p, String e) { 264 | name = n; 265 | phonenum = p; 266 | email = e; 267 | } 268 | } 269 | 270 | class NamePhone { 271 | String name; 272 | String phonenum; 273 | 274 | NamePhone(String n, String p) { 275 | name = n; 276 | phonenum = p; 277 | } 278 | } 279 | 280 | class StreamDemo7 { 281 | 282 | public static void main(String[] args) { 283 | 284 | // A list of names, phone numbers, and e-mail addresses. 285 | ArrayList myList = new ArrayList<>( ); 286 | 287 | myList.add(new NamePhoneEmail("Larry", "555-5555", 288 | "Larry@HerbSchildt.com")); 289 | myList.add(new NamePhoneEmail("James", "555-4444", 290 | "James@HerbSchildt.com")); 291 | myList.add(new NamePhoneEmail("Mary", "555-3333", 292 | "Mary@HerbSchildt.com")); 293 | 294 | // Map just the names and phone numbers to a new stream. 295 | Stream nameAndPhone = myList.stream().map( 296 | (a) -> new NamePhone(a.name,a.phonenum) 297 | ); 298 | 299 | // Use collect to create a List of the names and phone numbers. 300 | List npList = nameAndPhone.collect(Collectors.toList()); 301 | 302 | System.out.println("Names and phone numbers in a List:"); 303 | for(NamePhone e : npList) 304 | System.out.println(e.name + ": " + e.phonenum); 305 | 306 | // Obtain another mapping of the names and phone numbers. 307 | nameAndPhone = myList.stream().map( 308 | (a) -> new NamePhone(a.name,a.phonenum) 309 | ); 310 | 311 | // Now, create a Set by use of collect(). 312 | Set npSet = nameAndPhone.collect(Collectors.toSet()); 313 | 314 | System.out.println("\nNames and phone numbers in a Set:"); 315 | for(NamePhone e : npSet) 316 | System.out.println(e.name + ": " + e.phonenum); 317 | } 318 | } 319 | 320 | listing 8 321 | // Use an iterator with a stream. 322 | 323 | import java.util.*; 324 | import java.util.stream.*; 325 | 326 | class StreamDemo8 { 327 | 328 | public static void main(String[] args) { 329 | 330 | // Create a list of Strings. 331 | ArrayList myList = new ArrayList<>( ); 332 | myList.add("Alpha"); 333 | myList.add("Beta"); 334 | myList.add("Gamma"); 335 | myList.add("Delta"); 336 | myList.add("Phi"); 337 | myList.add("Omega"); 338 | 339 | // Obtain a Stream to the array list. 340 | Stream myStream = myList.stream(); 341 | 342 | // Obtain an iterator to the stream. 343 | Iterator itr = myStream.iterator(); 344 | 345 | // Iterate the elements in the stream. 346 | while(itr.hasNext()) 347 | System.out.println(itr.next()); 348 | } 349 | } 350 | 351 | listing 9 352 | // Use a Spliterator. 353 | 354 | import java.util.*; 355 | import java.util.stream.*; 356 | 357 | class StreamDemo9 { 358 | 359 | public static void main(String[] args) { 360 | 361 | // Create a list of Strings. 362 | ArrayList myList = new ArrayList<>( ); 363 | myList.add("Alpha"); 364 | myList.add("Beta"); 365 | myList.add("Gamma"); 366 | myList.add("Delta"); 367 | myList.add("Phi"); 368 | myList.add("Omega"); 369 | 370 | // Obtain a Stream to the array list. 371 | Stream myStream = myList.stream(); 372 | 373 | // Obtain a Spliterator. 374 | Spliterator splitItr = myStream.spliterator(); 375 | 376 | // Iterate the elements of the stream. 377 | while(splitItr.tryAdvance((n) -> System.out.println(n))); 378 | } 379 | } 380 | 381 | listing 10 382 | // Demonstrate trySplit(). 383 | 384 | import java.util.*; 385 | import java.util.stream.*; 386 | 387 | class StreamDemo10 { 388 | 389 | public static void main(String[] args) { 390 | 391 | // Create a list of Strings. 392 | ArrayList myList = new ArrayList<>( ); 393 | myList.add("Alpha"); 394 | myList.add("Beta"); 395 | myList.add("Gamma"); 396 | myList.add("Delta"); 397 | myList.add("Phi"); 398 | myList.add("Omega"); 399 | 400 | // Obtain a Stream to the array list. 401 | Stream myStream = myList.stream(); 402 | 403 | // Obtain a Spliterator. 404 | Spliterator splitItr = myStream.spliterator(); 405 | 406 | // Now, split the first iterator. 407 | Spliterator splitItr2 = splitItr.trySplit(); 408 | 409 | // If splitItr could be split, use splitItr2 first. 410 | if(splitItr2 != null) { 411 | System.out.println("Output from splitItr2: "); 412 | splitItr2.forEachRemaining((n) -> System.out.println(n)); 413 | } 414 | 415 | // Now, use the splitItr. 416 | System.out.println("\nOutput from splitItr: "); 417 | splitItr.forEachRemaining((n) -> System.out.println(n)); 418 | } 419 | } 420 | 421 | -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap5.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | // Demonstrate if-else-if statements. 3 | class IfElse { 4 | public static void main(String args[]) { 5 | int month = 4; // April 6 | String season; 7 | 8 | if(month == 12 || month == 1 || month == 2) 9 | season = "Winter"; 10 | else if(month == 3 || month == 4 || month == 5) 11 | season = "Spring"; 12 | else if(month == 6 || month == 7 || month == 8) 13 | season = "Summer"; 14 | else if(month == 9 || month == 10 || month == 11) 15 | season = "Autumn"; 16 | else 17 | season = "Bogus Month"; 18 | 19 | System.out.println("April is in the " + season + "."); 20 | } 21 | } 22 | 23 | listing 2 24 | // A simple example of the switch. 25 | class SampleSwitch { 26 | public static void main(String args[]) { 27 | for(int i=0; i<6; i++) 28 | switch(i) { 29 | case 0: 30 | System.out.println("i is zero."); 31 | break; 32 | case 1: 33 | System.out.println("i is one."); 34 | break; 35 | case 2: 36 | System.out.println("i is two."); 37 | break; 38 | case 3: 39 | System.out.println("i is three."); 40 | break; 41 | default: 42 | System.out.println("i is greater than 3."); 43 | } 44 | } 45 | } 46 | 47 | listing 3 48 | // In a switch, break statements are optional. 49 | class MissingBreak { 50 | public static void main(String args[]) { 51 | for(int i=0; i<12; i++) 52 | switch(i) { 53 | case 0: 54 | case 1: 55 | case 2: 56 | case 3: 57 | case 4: 58 | System.out.println("i is less than 5"); 59 | break; 60 | case 5: 61 | case 6: 62 | case 7: 63 | case 8: 64 | case 9: 65 | System.out.println("i is less than 10"); 66 | break; 67 | default: 68 | System.out.println("i is 10 or more."); 69 | } 70 | } 71 | } 72 | 73 | listing 4 74 | // An improved version of the season program. 75 | class Switch { 76 | public static void main(String args[]) { 77 | int month = 4; 78 | String season; 79 | 80 | switch (month) { 81 | case 12: 82 | case 1: 83 | case 2: 84 | season = "Winter"; 85 | break; 86 | case 3: 87 | case 4: 88 | case 5: 89 | season = "Spring"; 90 | break; 91 | case 6: 92 | case 7: 93 | case 8: 94 | season = "Summer"; 95 | break; 96 | case 9: 97 | case 10: 98 | case 11: 99 | season = "Autumn"; 100 | break; 101 | default: 102 | season = "Bogus Month"; 103 | } 104 | System.out.println("April is in the " + season + "."); 105 | } 106 | } 107 | 108 | listing 5 109 | // Use a string to control a switch statement. 110 | 111 | class StringSwitch { 112 | public static void main(String args[]) { 113 | 114 | String str = "two"; 115 | 116 | switch(str) { 117 | case "one": 118 | System.out.println("one"); 119 | break; 120 | case "two": 121 | System.out.println("two"); 122 | break; 123 | case "three": 124 | System.out.println("three"); 125 | break; 126 | default: 127 | System.out.println("no match"); 128 | break; 129 | } 130 | } 131 | } 132 | 133 | 134 | listing 6 135 | // Demonstrate the while loop. 136 | class While { 137 | public static void main(String args[]) { 138 | int n = 10; 139 | 140 | while(n > 0) { 141 | System.out.println("tick " + n); 142 | n--; 143 | } 144 | } 145 | } 146 | 147 | listing 7 148 | // The target of a loop can be empty. 149 | class NoBody { 150 | public static void main(String args[]) { 151 | int i, j; 152 | 153 | i = 100; 154 | j = 200; 155 | 156 | // find midpoint between i and j 157 | while(++i < --j) ; // no body in this loop 158 | 159 | System.out.println("Midpoint is " + i); 160 | } 161 | } 162 | 163 | listing 8 164 | // Demonstrate the do-while loop. 165 | class DoWhile { 166 | public static void main(String args[]) { 167 | int n = 10; 168 | 169 | do { 170 | System.out.println("tick " + n); 171 | n--; 172 | } while(n > 0); 173 | } 174 | } 175 | 176 | listing 9 177 | // Using a do-while to process a menu selection -- a simple help system. 178 | class Menu { 179 | public static void main(String args[]) 180 | throws java.io.IOException { 181 | char choice; 182 | 183 | do { 184 | System.out.println("Help on:"); 185 | System.out.println(" 1. if"); 186 | System.out.println(" 2. switch"); 187 | System.out.println(" 3. while"); 188 | System.out.println(" 4. do-while"); 189 | System.out.println(" 5. for\n"); 190 | System.out.println("Choose one:"); 191 | choice = (char) System.in.read(); 192 | } while( choice < '1' || choice > '5'); 193 | 194 | System.out.println("\n"); 195 | 196 | switch(choice) { 197 | case '1': 198 | System.out.println("The if:\n"); 199 | System.out.println("if(condition) statement;"); 200 | System.out.println("else statement;"); 201 | break; 202 | case '2': 203 | System.out.println("The switch:\n"); 204 | System.out.println("switch(expression) {"); 205 | System.out.println(" case constant:"); 206 | System.out.println(" statement sequence"); 207 | System.out.println(" break;"); 208 | System.out.println(" // ..."); 209 | System.out.println("}"); 210 | break; 211 | case '3': 212 | System.out.println("The while:\n"); 213 | System.out.println("while(condition) statement;"); 214 | break; 215 | case '4': 216 | System.out.println("The do-while:\n"); 217 | System.out.println("do {"); 218 | System.out.println(" statement;"); 219 | System.out.println("} while (condition);"); 220 | break; 221 | case '5': 222 | System.out.println("The for:\n"); 223 | System.out.print("for(init; condition; iteration)"); 224 | System.out.println(" statement;"); 225 | break; 226 | } 227 | } 228 | } 229 | 230 | listing 10 231 | // Demonstrate the for loop. 232 | class ForTick { 233 | public static void main(String args[]) { 234 | int n; 235 | 236 | for(n=10; n>0; n--) 237 | System.out.println("tick " + n); 238 | } 239 | } 240 | 241 | listing 11 242 | // Declare a loop control variable inside the for. 243 | class ForTick { 244 | public static void main(String args[]) { 245 | 246 | // here, n is declared inside of the for loop 247 | for(int n=10; n>0; n--) 248 | System.out.println("tick " + n); 249 | } 250 | } 251 | 252 | listing 12 253 | // Test for primes. 254 | class FindPrime { 255 | public static void main(String args[]) { 256 | int num; 257 | boolean isPrime; 258 | 259 | num = 14; 260 | 261 | if(num < 2) isPrime = false; 262 | else isPrime = true; 263 | 264 | for(int i=2; i <= num/i; i++) { 265 | if((num % i) == 0) { 266 | isPrime = false; 267 | break; 268 | } 269 | } 270 | 271 | if(isPrime) System.out.println("Prime"); 272 | else System.out.println("Not Prime"); 273 | } 274 | } 275 | 276 | listing 13 277 | class Sample { 278 | public static void main(String args[]) { 279 | int a, b; 280 | 281 | b = 4; 282 | for(a=1; a i) { 545 | System.out.println(); 546 | continue outer; 547 | } 548 | System.out.print(" " + (i * j)); 549 | } 550 | } 551 | System.out.println(); 552 | } 553 | } 554 | 555 | listing 30 556 | // Demonstrate return. 557 | class Return { 558 | public static void main(String args[]) { 559 | boolean t = true; 560 | 561 | System.out.println("Before the return."); 562 | 563 | if(t) return; // return to caller 564 | 565 | System.out.println("This won't execute."); 566 | } 567 | } 568 | 569 |  -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap11.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | // Controlling the main Thread. 3 | class CurrentThreadDemo { 4 | public static void main(String args[]) { 5 | Thread t = Thread.currentThread(); 6 | 7 | System.out.println("Current thread: " + t); 8 | 9 | // change the name of the thread 10 | t.setName("My Thread"); 11 | System.out.println("After name change: " + t); 12 | 13 | try { 14 | for(int n = 5; n > 0; n--) { 15 | System.out.println(n); 16 | Thread.sleep(1000); 17 | } 18 | } catch (InterruptedException e) { 19 | System.out.println("Main thread interrupted"); 20 | } 21 | } 22 | } 23 | 24 | listing 2 25 | // Create a second thread. 26 | class NewThread implements Runnable { 27 | Thread t; 28 | 29 | NewThread() { 30 | // Create a new, second thread 31 | t = new Thread(this, "Demo Thread"); 32 | System.out.println("Child thread: " + t); 33 | t.start(); // Start the thread 34 | } 35 | 36 | // This is the entry point for the second thread. 37 | public void run() { 38 | try { 39 | for(int i = 5; i > 0; i--) { 40 | System.out.println("Child Thread: " + i); 41 | Thread.sleep(500); 42 | } 43 | } catch (InterruptedException e) { 44 | System.out.println("Child interrupted."); 45 | } 46 | System.out.println("Exiting child thread."); 47 | } 48 | } 49 | 50 | class ThreadDemo { 51 | public static void main(String args[]) { 52 | new NewThread(); // create a new thread 53 | 54 | try { 55 | for(int i = 5; i > 0; i--) { 56 | System.out.println("Main Thread: " + i); 57 | Thread.sleep(1000); 58 | } 59 | } catch (InterruptedException e) { 60 | System.out.println("Main thread interrupted."); 61 | } 62 | System.out.println("Main thread exiting."); 63 | } 64 | } 65 | 66 | listing 3 67 | // Create a second thread by extending Thread 68 | class NewThread extends Thread { 69 | 70 | NewThread() { 71 | // Create a new, second thread 72 | super("Demo Thread"); 73 | System.out.println("Child thread: " + this); 74 | start(); // Start the thread 75 | } 76 | 77 | // This is the entry point for the second thread. 78 | public void run() { 79 | try { 80 | for(int i = 5; i > 0; i--) { 81 | System.out.println("Child Thread: " + i); 82 | Thread.sleep(500); 83 | } 84 | } catch (InterruptedException e) { 85 | System.out.println("Child interrupted."); 86 | } 87 | System.out.println("Exiting child thread."); 88 | } 89 | } 90 | 91 | class ExtendThread { 92 | public static void main(String args[]) { 93 | new NewThread(); // create a new thread 94 | 95 | try { 96 | for(int i = 5; i > 0; i--) { 97 | System.out.println("Main Thread: " + i); 98 | Thread.sleep(1000); 99 | } 100 | } catch (InterruptedException e) { 101 | System.out.println("Main thread interrupted."); 102 | } 103 | System.out.println("Main thread exiting."); 104 | } 105 | } 106 | 107 | listing 4 108 | // Create multiple threads. 109 | class NewThread implements Runnable { 110 | String name; // name of thread 111 | Thread t; 112 | 113 | NewThread(String threadname) { 114 | name = threadname; 115 | t = new Thread(this, name); 116 | System.out.println("New thread: " + t); 117 | t.start(); // Start the thread 118 | } 119 | 120 | // This is the entry point for thread. 121 | public void run() { 122 | try { 123 | for(int i = 5; i > 0; i--) { 124 | System.out.println(name + ": " + i); 125 | Thread.sleep(1000); 126 | } 127 | } catch (InterruptedException e) { 128 | System.out.println(name + "Interrupted"); 129 | } 130 | System.out.println(name + " exiting."); 131 | } 132 | } 133 | 134 | class MultiThreadDemo { 135 | public static void main(String args[]) { 136 | new NewThread("One"); // start threads 137 | new NewThread("Two"); 138 | new NewThread("Three"); 139 | 140 | try { 141 | // wait for other threads to end 142 | Thread.sleep(10000); 143 | } catch (InterruptedException e) { 144 | System.out.println("Main thread Interrupted"); 145 | } 146 | 147 | System.out.println("Main thread exiting."); 148 | } 149 | } 150 | 151 | listing 5 152 | // Using join() to wait for threads to finish. 153 | class NewThread implements Runnable { 154 | String name; // name of thread 155 | Thread t; 156 | 157 | NewThread(String threadname) { 158 | name = threadname; 159 | t = new Thread(this, name); 160 | System.out.println("New thread: " + t); 161 | t.start(); // Start the thread 162 | } 163 | 164 | // This is the entry point for thread. 165 | public void run() { 166 | try { 167 | for(int i = 5; i > 0; i--) { 168 | System.out.println(name + ": " + i); 169 | Thread.sleep(1000); 170 | } 171 | } catch (InterruptedException e) { 172 | System.out.println(name + " interrupted."); 173 | } 174 | System.out.println(name + " exiting."); 175 | } 176 | } 177 | 178 | class DemoJoin { 179 | public static void main(String args[]) { 180 | NewThread ob1 = new NewThread("One"); 181 | NewThread ob2 = new NewThread("Two"); 182 | NewThread ob3 = new NewThread("Three"); 183 | 184 | System.out.println("Thread One is alive: " 185 | + ob1.t.isAlive()); 186 | System.out.println("Thread Two is alive: " 187 | + ob2.t.isAlive()); 188 | System.out.println("Thread Three is alive: " 189 | + ob3.t.isAlive()); 190 | // wait for threads to finish 191 | try { 192 | System.out.println("Waiting for threads to finish."); 193 | ob1.t.join(); 194 | ob2.t.join(); 195 | ob3.t.join(); 196 | } catch (InterruptedException e) { 197 | System.out.println("Main thread Interrupted"); 198 | } 199 | 200 | System.out.println("Thread One is alive: " 201 | + ob1.t.isAlive()); 202 | System.out.println("Thread Two is alive: " 203 | + ob2.t.isAlive()); 204 | System.out.println("Thread Three is alive: " 205 | + ob3.t.isAlive()); 206 | 207 | System.out.println("Main thread exiting."); 208 | } 209 | } 210 | 211 | listing 6 212 | // This program is not synchronized. 213 | class Callme { 214 | void call(String msg) { 215 | System.out.print("[" + msg); 216 | try { 217 | Thread.sleep(1000); 218 | } catch(InterruptedException e) { 219 | System.out.println("Interrupted"); 220 | } 221 | System.out.println("]"); 222 | } 223 | } 224 | 225 | class Caller implements Runnable { 226 | String msg; 227 | Callme target; 228 | Thread t; 229 | 230 | public Caller(Callme targ, String s) { 231 | target = targ; 232 | msg = s; 233 | t = new Thread(this); 234 | t.start(); 235 | } 236 | 237 | public void run() { 238 | target.call(msg); 239 | } 240 | } 241 | 242 | class Synch { 243 | public static void main(String args[]) { 244 | Callme target = new Callme(); 245 | Caller ob1 = new Caller(target, "Hello"); 246 | Caller ob2 = new Caller(target, "Synchronized"); 247 | Caller ob3 = new Caller(target, "World"); 248 | 249 | // wait for threads to end 250 | try { 251 | ob1.t.join(); 252 | ob2.t.join(); 253 | ob3.t.join(); 254 | } catch(InterruptedException e) { 255 | System.out.println("Interrupted"); 256 | } 257 | } 258 | } 259 | 260 | listing 7 261 | // This program uses a synchronized block. 262 | class Callme { 263 | void call(String msg) { 264 | System.out.print("[" + msg); 265 | try { 266 | Thread.sleep(1000); 267 | } catch (InterruptedException e) { 268 | System.out.println("Interrupted"); 269 | } 270 | System.out.println("]"); 271 | } 272 | } 273 | 274 | class Caller implements Runnable { 275 | String msg; 276 | Callme target; 277 | Thread t; 278 | 279 | public Caller(Callme targ, String s) { 280 | target = targ; 281 | msg = s; 282 | t = new Thread(this); 283 | t.start(); 284 | } 285 | 286 | // synchronize calls to call() 287 | public void run() { 288 | synchronized(target) { // synchronized block 289 | target.call(msg); 290 | } 291 | } 292 | } 293 | 294 | class Synch1 { 295 | public static void main(String args[]) { 296 | Callme target = new Callme(); 297 | Caller ob1 = new Caller(target, "Hello"); 298 | Caller ob2 = new Caller(target, "Synchronized"); 299 | Caller ob3 = new Caller(target, "World"); 300 | 301 | // wait for threads to end 302 | try { 303 | ob1.t.join(); 304 | ob2.t.join(); 305 | ob3.t.join(); 306 | } catch(InterruptedException e) { 307 | System.out.println("Interrupted"); 308 | } 309 | } 310 | } 311 | 312 | listing 8 313 | // An incorrect implementation of a producer and consumer. 314 | class Q { 315 | int n; 316 | 317 | synchronized int get() { 318 | System.out.println("Got: " + n); 319 | return n; 320 | } 321 | 322 | synchronized void put(int n) { 323 | this.n = n; 324 | System.out.println("Put: " + n); 325 | } 326 | } 327 | 328 | class Producer implements Runnable { 329 | Q q; 330 | 331 | Producer(Q q) { 332 | this.q = q; 333 | new Thread(this, "Producer").start(); 334 | } 335 | 336 | public void run() { 337 | int i = 0; 338 | 339 | while(true) { 340 | q.put(i++); 341 | } 342 | } 343 | } 344 | 345 | class Consumer implements Runnable { 346 | Q q; 347 | 348 | Consumer(Q q) { 349 | this.q = q; 350 | new Thread(this, "Consumer").start(); 351 | } 352 | 353 | public void run() { 354 | while(true) { 355 | q.get(); 356 | } 357 | } 358 | } 359 | 360 | class PC { 361 | public static void main(String args[]) { 362 | Q q = new Q(); 363 | new Producer(q); 364 | new Consumer(q); 365 | 366 | System.out.println("Press Control-C to stop."); 367 | } 368 | } 369 | 370 | listing 9 371 | // A correct implementation of a producer and consumer. 372 | class Q { 373 | int n; 374 | boolean valueSet = false; 375 | 376 | synchronized int get() { 377 | while(!valueSet) 378 | try { 379 | wait(); 380 | 381 | } catch(InterruptedException e) { 382 | System.out.println("InterruptedException caught"); 383 | } 384 | 385 | System.out.println("Got: " + n); 386 | valueSet = false; 387 | notify(); 388 | return n; 389 | } 390 | 391 | synchronized void put(int n) { 392 | while(valueSet) 393 | try { 394 | wait(); 395 | } catch(InterruptedException e) { 396 | System.out.println("InterruptedException caught"); 397 | } 398 | 399 | this.n = n; 400 | valueSet = true; 401 | System.out.println("Put: " + n); 402 | notify(); 403 | } 404 | } 405 | 406 | class Producer implements Runnable { 407 | Q q; 408 | 409 | Producer(Q q) { 410 | this.q = q; 411 | new Thread(this, "Producer").start(); 412 | } 413 | 414 | public void run() { 415 | int i = 0; 416 | 417 | while(true) { 418 | q.put(i++); 419 | } 420 | } 421 | } 422 | 423 | class Consumer implements Runnable { 424 | Q q; 425 | 426 | Consumer(Q q) { 427 | this.q = q; 428 | new Thread(this, "Consumer").start(); 429 | } 430 | 431 | public void run() { 432 | while(true) { 433 | q.get(); 434 | } 435 | } 436 | } 437 | 438 | class PCFixed { 439 | public static void main(String args[]) { 440 | Q q = new Q(); 441 | new Producer(q); 442 | new Consumer(q); 443 | 444 | System.out.println("Press Control-C to stop."); 445 | } 446 | } 447 | 448 | listing 10 449 | // An example of deadlock. 450 | class A { 451 | synchronized void foo(B b) { 452 | String name = Thread.currentThread().getName(); 453 | 454 | System.out.println(name + " entered A.foo"); 455 | 456 | try { 457 | Thread.sleep(1000); 458 | } catch(Exception e) { 459 | System.out.println("A Interrupted"); 460 | } 461 | 462 | System.out.println(name + " trying to call B.last()"); 463 | b.last(); 464 | } 465 | 466 | synchronized void last() { 467 | System.out.println("Inside A.last"); 468 | } 469 | } 470 | 471 | class B { 472 | synchronized void bar(A a) { 473 | String name = Thread.currentThread().getName(); 474 | System.out.println(name + " entered B.bar"); 475 | 476 | try { 477 | Thread.sleep(1000); 478 | } catch(Exception e) { 479 | System.out.println("B Interrupted"); 480 | } 481 | 482 | System.out.println(name + " trying to call A.last()"); 483 | a.last(); 484 | } 485 | 486 | synchronized void last() { 487 | System.out.println("Inside A.last"); 488 | } 489 | } 490 | 491 | class Deadlock implements Runnable { 492 | A a = new A(); 493 | B b = new B(); 494 | 495 | Deadlock() { 496 | Thread.currentThread().setName("MainThread"); 497 | Thread t = new Thread(this, "RacingThread"); 498 | t.start(); 499 | 500 | a.foo(b); // get lock on a in this thread. 501 | System.out.println("Back in main thread"); 502 | } 503 | 504 | public void run() { 505 | b.bar(a); // get lock on b in other thread. 506 | System.out.println("Back in other thread"); 507 | } 508 | 509 | public static void main(String args[]) { 510 | new Deadlock(); 511 | } 512 | } 513 | 514 | listing 11 515 | // Suspending and resuming a thread for Java 2 516 | class NewThread implements Runnable { 517 | String name; // name of thread 518 | Thread t; 519 | boolean suspendFlag; 520 | 521 | NewThread(String threadname) { 522 | name = threadname; 523 | t = new Thread(this, name); 524 | System.out.println("New thread: " + t); 525 | suspendFlag = false; 526 | t.start(); // Start the thread 527 | } 528 | 529 | // This is the entry point for thread. 530 | public void run() { 531 | try { 532 | for(int i = 15; i > 0; i--) { 533 | System.out.println(name + ": " + i); 534 | Thread.sleep(200); 535 | synchronized(this) { 536 | while(suspendFlag) { 537 | wait(); 538 | } 539 | } 540 | } 541 | } catch (InterruptedException e) { 542 | System.out.println(name + " interrupted."); 543 | } 544 | System.out.println(name + " exiting."); 545 | } 546 | 547 | synchronized void mysuspend() { 548 | suspendFlag = true; 549 | } 550 | 551 | synchronized void myresume() { 552 | suspendFlag = false; 553 | notify(); 554 | } 555 | } 556 | 557 | class SuspendResume { 558 | public static void main(String args[]) { 559 | NewThread ob1 = new NewThread("One"); 560 | NewThread ob2 = new NewThread("Two"); 561 | 562 | try { 563 | Thread.sleep(1000); 564 | ob1.mysuspend(); 565 | System.out.println("Suspending thread One"); 566 | Thread.sleep(1000); 567 | ob1.myresume(); 568 | System.out.println("Resuming thread One"); 569 | ob2.mysuspend(); 570 | System.out.println("Suspending thread Two"); 571 | Thread.sleep(1000); 572 | ob2.myresume(); 573 | System.out.println("Resuming thread Two"); 574 | } catch (InterruptedException e) { 575 | System.out.println("Main thread Interrupted"); 576 | } 577 | 578 | // wait for threads to finish 579 | try { 580 | System.out.println("Waiting for threads to finish."); 581 | ob1.t.join(); 582 | ob2.t.join(); 583 | } catch (InterruptedException e) { 584 | System.out.println("Main thread Interrupted"); 585 | } 586 | 587 | System.out.println("Main thread exiting."); 588 | } 589 | } 590 | 591 |  -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap9.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | // A simple package 3 | package MyPack; 4 | 5 | class Balance { 6 | String name; 7 | double bal; 8 | 9 | Balance(String n, double b) { 10 | name = n; 11 | bal = b; 12 | } 13 | 14 | void show() { 15 | if(bal<0) 16 | System.out.print("-->> "); 17 | System.out.println(name + ": $" + bal); 18 | } 19 | } 20 | 21 | class AccountBalance { 22 | public static void main(String args[]) { 23 | Balance current[] = new Balance[3]; 24 | 25 | current[0] = new Balance("K. J. Fielding", 123.23); 26 | current[1] = new Balance("Will Tell", 157.02); 27 | current[2] = new Balance("Tom Jackson", -12.33); 28 | 29 | for(int i=0; i<3; i++) current[i].show(); 30 | } 31 | } 32 | 33 | listing 2 34 | package p1; 35 | 36 | public class Protection { 37 | int n = 1; 38 | private int n_pri = 2; 39 | protected int n_pro = 3; 40 | public int n_pub = 4; 41 | 42 | public Protection() { 43 | System.out.println("base constructor"); 44 | System.out.println("n = " + n); 45 | System.out.println("n_pri = " + n_pri); 46 | System.out.println("n_pro = " + n_pro); 47 | System.out.println("n_pub = " + n_pub); 48 | } 49 | } 50 | 51 | class Derived extends Protection { 52 | Derived() { 53 | System.out.println("derived constructor"); 54 | System.out.println("n = " + n); 55 | 56 | // class only 57 | // System.out.println("n_pri = " + n_pri); 58 | 59 | System.out.println("n_pro = " + n_pro); 60 | System.out.println("n_pub = " + n_pub); 61 | } 62 | } 63 | 64 | class SamePackage { 65 | SamePackage() { 66 | Protection p = new Protection(); 67 | System.out.println("same package constructor"); 68 | System.out.println("n = " + p.n); 69 | 70 | // class only 71 | // System.out.println("n_pri = " + p.n_pri); 72 | 73 | System.out.println("n_pro = " + p.n_pro); 74 | System.out.println("n_pub = " + p.n_pub); 75 | } 76 | } 77 | 78 | listing 3 79 | package p2; 80 | 81 | class Protection2 extends p1.Protection { 82 | Protection2() { 83 | System.out.println("derived other package constructor"); 84 | 85 | // class or package only 86 | // System.out.println("n = " + n); 87 | 88 | // class only 89 | // System.out.println("n_pri = " + n_pri); 90 | 91 | System.out.println("n_pro = " + n_pro); 92 | System.out.println("n_pub = " + n_pub); 93 | } 94 | } 95 | 96 | class OtherPackage { 97 | OtherPackage() { 98 | p1.Protection p = new p1.Protection(); 99 | System.out.println("other package constructor"); 100 | 101 | // class or package only 102 | // System.out.println("n = " + p.n); 103 | 104 | // class only 105 | // System.out.println("n_pri = " + p.n_pri); 106 | 107 | // class, subclass or package only 108 | // System.out.println("n_pro = " + p.n_pro); 109 | 110 | System.out.println("n_pub = " + p.n_pub); 111 | } 112 | } 113 | 114 | listing 4 115 | // Demo package p1. 116 | package p1; 117 | 118 | // Instantiate the various classes in p1. 119 | public class Demo { 120 | public static void main(String args[]) { 121 | Protection ob1 = new Protection(); 122 | Derived ob2 = new Derived(); 123 | SamePackage ob3 = new SamePackage(); 124 | } 125 | } 126 | 127 | 128 | listing 5 129 | // Demo package p2. 130 | package p2; 131 | 132 | // Instantiate the various classes in p2. 133 | public class Demo { 134 | public static void main(String args[]) { 135 | Protection2 ob1 = new Protection2(); 136 | OtherPackage ob2 = new OtherPackage(); 137 | } 138 | } 139 | 140 | listing 6 141 | import java.util.*; 142 | class MyDate extends Date { 143 | } 144 | 145 | listing 7 146 | class MyDate extends java.util.Date { 147 | } 148 | 149 | listing 8 150 | package MyPack; 151 | 152 | /* Now, the Balance class, its constructor, and its 153 | show() method are public. This means that they can 154 | be used by non-subclass code outside their package. 155 | */ 156 | public class Balance { 157 | String name; 158 | double bal; 159 | 160 | public Balance(String n, double b) { 161 | name = n; 162 | bal = b; 163 | } 164 | 165 | public void show() { 166 | if(bal<0) 167 | System.out.print("-->> "); 168 | System.out.println(name + ": $" + bal); 169 | } 170 | } 171 | 172 | listing 9 173 | import MyPack.*; 174 | 175 | class TestBalance { 176 | public static void main(String args[]) { 177 | 178 | /* Because Balance is public, you may use Balance 179 | class and call its constructor. */ 180 | Balance test = new Balance("J. J. Jaspers", 99.88); 181 | 182 | test.show(); // you may also call show() 183 | } 184 | } 185 | 186 | listing 10 187 | interface Callback { 188 | void callback(int param); 189 | } 190 | 191 | listing 11 192 | class Client implements Callback { 193 | // Implement Callback's interface 194 | public void callback(int p) { 195 | System.out.println("callback called with " + p); 196 | } 197 | } 198 | 199 | listing 12 200 | class Client implements Callback { 201 | // Implement Callback's interface 202 | public void callback(int p) { 203 | System.out.println("callback called with " + p); 204 | } 205 | 206 | void nonIfaceMeth() { 207 | System.out.println("Classes that implement interfaces " + 208 | "may also define other members, too."); 209 | } 210 | } 211 | 212 | listing 13 213 | class TestIface { 214 | public static void main(String args[]) { 215 | Callback c = new Client(); 216 | c.callback(42); 217 | } 218 | } 219 | 220 | listing 14 221 | // Another implementation of Callback. 222 | class AnotherClient implements Callback { 223 | // Implement Callback's interface 224 | public void callback(int p) { 225 | System.out.println("Another version of callback"); 226 | System.out.println("p squared is " + (p*p)); 227 | } 228 | } 229 | 230 | listing 15 231 | class TestIface2 { 232 | public static void main(String args[]) { 233 | Callback c = new Client(); 234 | AnotherClient ob = new AnotherClient(); 235 | 236 | c.callback(42); 237 | 238 | c = ob; // c now refers to AnotherClient object 239 | c.callback(42); 240 | } 241 | } 242 | 243 | listing 16 244 | abstract class Incomplete implements Callback { 245 | int a, b; 246 | void show() { 247 | System.out.println(a + " " + b); 248 | } 249 | // ... 250 | } 251 | 252 | listing 17 253 | // A nested interface example. 254 | 255 | // This class contains a member interface. 256 | class A { 257 | // this is a nested interface 258 | public interface NestedIF { 259 | boolean isNotNegative(int x); 260 | } 261 | } 262 | 263 | // B implements the nested interface. 264 | class B implements A.NestedIF { 265 | public boolean isNotNegative(int x) { 266 | return x < 0 ? false : true; 267 | } 268 | } 269 | 270 | class NestedIFDemo { 271 | public static void main(String args[]) { 272 | 273 | // use a nested interface reference 274 | A.NestedIF nif = new B(); 275 | 276 | if(nif.isNotNegative(10)) 277 | System.out.println("10 is not negative"); 278 | if(nif.isNotNegative(-12)) 279 | System.out.println("this won't be displayed"); 280 | } 281 | } 282 | 283 | 284 | listing 18 285 | // Define an integer stack interface. 286 | interface IntStack { 287 | void push(int item); // store an item 288 | int pop(); // retrieve an item 289 | } 290 | 291 | listing 19 292 | // An implementation of IntStack that uses fixed storage. 293 | class FixedStack implements IntStack { 294 | private int stck[]; 295 | private int tos; 296 | 297 | // allocate and initialize stack 298 | FixedStack(int size) { 299 | stck = new int[size]; 300 | tos = -1; 301 | } 302 | 303 | // Push an item onto the stack 304 | public void push(int item) { 305 | if(tos==stck.length-1) // use length member 306 | System.out.println("Stack is full."); 307 | else 308 | stck[++tos] = item; 309 | } 310 | 311 | // Pop an item from the stack 312 | public int pop() { 313 | if(tos < 0) { 314 | System.out.println("Stack underflow."); 315 | return 0; 316 | } 317 | else 318 | return stck[tos--]; 319 | } 320 | } 321 | 322 | class IFTest { 323 | public static void main(String args[]) { 324 | FixedStack mystack1 = new FixedStack(5); 325 | FixedStack mystack2 = new FixedStack(8); 326 | 327 | // push some numbers onto the stack 328 | for(int i=0; i<5; i++) mystack1.push(i); 329 | for(int i=0; i<8; i++) mystack2.push(i); 330 | 331 | // pop those numbers off the stack 332 | System.out.println("Stack in mystack1:"); 333 | for(int i=0; i<5; i++) 334 | System.out.println(mystack1.pop()); 335 | 336 | System.out.println("Stack in mystack2:"); 337 | for(int i=0; i<8; i++) 338 | System.out.println(mystack2.pop()); 339 | } 340 | } 341 | 342 | listing 20 343 | // Implement a "growable" stack. 344 | class DynStack implements IntStack { 345 | private int stck[]; 346 | private int tos; 347 | 348 | // allocate and initialize stack 349 | DynStack(int size) { 350 | stck = new int[size]; 351 | tos = -1; 352 | } 353 | 354 | // Push an item onto the stack 355 | public void push(int item) { 356 | // if stack is full, allocate a larger stack 357 | if(tos==stck.length-1) { 358 | int temp[] = new int[stck.length * 2]; // double size 359 | for(int i=0; i 341 | 342 | */ 343 | 344 | public class SimpleApplet extends Applet { 345 | public void paint(Graphics g) { 346 | g.drawString("A Simple Applet", 20, 20); 347 | } 348 | } 349 | 350 | listing 13 351 | // Demonstrate instanceof operator. 352 | class A { 353 | int i, j; 354 | } 355 | class B { 356 | int i, j; 357 | } 358 | class C extends A { 359 | int k; 360 | } 361 | class D extends A { 362 | int k; 363 | } 364 | class InstanceOf { 365 | public static void main(String args[]) { 366 | A a = new A(); 367 | B b = new B(); 368 | C c = new C(); 369 | D d = new D(); 370 | if(a instanceof A) 371 | System.out.println("a is instance of A"); 372 | if(b instanceof B) 373 | System.out.println("b is instance of B"); 374 | if(c instanceof C) 375 | System.out.println("c is instance of C"); 376 | if(c instanceof A) 377 | System.out.println("c can be cast to A"); 378 | if(a instanceof C) 379 | System.out.println("a can be cast to C"); 380 | System.out.println(); 381 | // compare types of derived types 382 | A ob; 383 | ob = d; // A reference to d 384 | System.out.println("ob now refers to d"); 385 | if(ob instanceof D) 386 | System.out.println("ob is instance of D"); 387 | System.out.println(); 388 | ob = c; // A reference to c 389 | System.out.println("ob now refers to c"); 390 | if(ob instanceof D) 391 | System.out.println("ob can be cast to D"); 392 | else 393 | System.out.println("ob cannot be cast to D"); 394 | if(ob instanceof A) 395 | System.out.println("ob can be cast to A"); 396 | System.out.println(); 397 | // all objects can be cast to Object 398 | if(a instanceof Object) 399 | System.out.println("a may be cast to Object"); 400 | if(b instanceof Object) 401 | System.out.println("b may be cast to Object"); 402 | if(c instanceof Object) 403 | System.out.println("c may be cast to Object"); 404 | if(d instanceof Object) 405 | System.out.println("d may be cast to Object"); 406 | } 407 | } 408 | 409 | listing 14 410 | // A simple example that uses a native method. 411 | public class NativeDemo { 412 | int i; 413 | public static void main(String args[]) { 414 | NativeDemo ob = new NativeDemo(); 415 | ob.i = 10; 416 | System.out.println("This is ob.i before the native method:" + 417 | ob.i); 418 | ob.test(); // call a native method 419 | System.out.println("This is ob.i after the native method:" + 420 | ob.i); 421 | } 422 | // declare native method 423 | public native void test() ; 424 | // load DLL that contains static method 425 | static { 426 | System.loadLibrary("NativeDemo"); 427 | } 428 | } 429 | 430 | listing 15 431 | /* DO NOT EDIT THIS FILE - it is machine generated */ 432 | #include 433 | /* Header for class NativeDemo */ 434 | 435 | #ifndef _Included_NativeDemo 436 | #define _Included_NativeDemo 437 | #ifdef _ _cplusplus 438 | extern "C" { 439 | #endif 440 | /* 441 | * Class: NativeDemo 442 | * Method: test 443 | * Signature: ()V 444 | */ 445 | JNIEXPORT void JNICALL Java_NativeDemo_test 446 | (JNIEnv *, jobject); 447 | 448 | #ifdef _ _cplusplus 449 | } 450 | #endif 451 | #endif 452 | 453 | listing 16 454 | /* This file contains the C version of the 455 | test() method. 456 | */ 457 | 458 | #include 459 | #include "NativeDemo.h" 460 | #include 461 | 462 | JNIEXPORT void JNICALL Java_NativeDemo_test(JNIEnv *env, jobject obj) 463 | { 464 | jclass cls; 465 | jfieldID fid; 466 | jint i; 467 | 468 | printf("Starting the native method.\n"); 469 | cls = (*env)->GetObjectClass(env, obj); 470 | fid = (*env)->GetFieldID(env, cls, "i", "I"); 471 | 472 | if(fid == 0) { 473 | printf("Could not get field id.\n"); 474 | return; 475 | } 476 | 477 | i = (*env)->GetIntField(env, obj, fid); 478 | printf("i = %d\n", i); 479 | (*env)->SetIntField(env, obj, fid, 2*i); 480 | printf("Ending the native method.\n"); 481 | } 482 | 483 | listing 17 484 | // Demonstrate assert. 485 | class AssertDemo { 486 | static int val = 3; 487 | 488 | // Return an integer. 489 | static int getnum() { 490 | return val--; 491 | } 492 | 493 | public static void main(String args[]) 494 | { 495 | int n; 496 | 497 | for(int i=0; i < 10; i++) { 498 | n = getnum(); 499 | 500 | assert n > 0; // will fail when n is 0 501 | 502 | System.out.println("n is " + n); 503 | } 504 | } 505 | } 506 | 507 | listing 18 508 | // A poor way to use assert!!! 509 | class AssertDemo { 510 | // get a random number generator 511 | static int val = 3; 512 | 513 | // Return an integer. 514 | static int getnum() { 515 | return val--; 516 | } 517 | 518 | public static void main(String args[]) 519 | { 520 | int n = 0; 521 | 522 | for(int i=0; i < 10; i++) { 523 | 524 | assert (n = getnum()) > 0; // This is not a good idea! 525 | 526 | System.out.println("n is " + n); 527 | } 528 | } 529 | } 530 | 531 | listing 19 532 | // Compute the hypotenuse of a right triangle. 533 | class Hypot { 534 | public static void main(String args[]) { 535 | double side1, side2; 536 | double hypot; 537 | side1 = 3.0; 538 | side2 = 4.0; 539 | 540 | // Notice how sqrt() and pow() must be qualified by 541 | // their class name, which is Math. 542 | hypot = Math.sqrt(Math.pow(side1, 2) + 543 | Math.pow(side2, 2)); 544 | 545 | System.out.println("Given sides of lengths " + 546 | side1 + " and " + side2 + 547 | " the hypotenuse is " + 548 | hypot); 549 | } 550 | } 551 | 552 | listing 20 553 | // Use static import to bring sqrt() and pow() into view. 554 | import static java.lang.Math.sqrt; 555 | import static java.lang.Math.pow; 556 | 557 | // Compute the hypotenuse of a right triangle. 558 | class Hypot { 559 | public static void main(String args[]) { 560 | double side1, side2; 561 | double hypot; 562 | 563 | side1 = 3.0; 564 | side2 = 4.0; 565 | 566 | // Here, sqrt() and pow() can be called by themselves, 567 | // without their class name. 568 | hypot = sqrt(pow(side1, 2) + pow(side2, 2)); 569 | 570 | System.out.println("Given sides of lengths " + 571 | side1 + " and " + side2 + 572 | " the hypotenuse is " + 573 | hypot); 574 | } 575 | } 576 | 577 | listing 21 578 | class MyClass { 579 | int a; 580 | int b; 581 | 582 | // initialize a and b individually 583 | MyClass(int i, int j) { 584 | a = i; 585 | b = j; 586 | } 587 | 588 | // initialize a and b to the same value 589 | MyClass(int i) { 590 | a = i; 591 | b = i; 592 | } 593 | 594 | // give a and b default values of 0 595 | MyClass( ) { 596 | a = 0; 597 | b = 0; 598 | } 599 | } 600 | 601 | listing 22 602 | class MyClass { 603 | int a; 604 | int b; 605 | 606 | // initialize a and b individually 607 | MyClass(int i, int j) { 608 | a = i; 609 | b = j; 610 | } 611 | 612 | // initialize a and b to the same value 613 | MyClass(int i) { 614 | this(i, i); // invokes MyClass(i, i) 615 | } 616 | 617 | // give a and b default values of 0 618 | MyClass( ) { 619 | this(0); // invokes MyClass(0) 620 | } 621 | } 622 | 623 | -------------------------------------------------------------------------------- /Java The Complete Reference Ninth Edition SourceCode/Chap36.lst: -------------------------------------------------------------------------------- 1 | listing 1 2 | // Demonstrate Menus 3 | 4 | import javafx.application.*; 5 | import javafx.scene.*; 6 | import javafx.stage.*; 7 | import javafx.scene.layout.*; 8 | import javafx.scene.control.*; 9 | import javafx.event.*; 10 | import javafx.geometry.*; 11 | 12 | public class MenuDemo extends Application { 13 | 14 | Label response; 15 | 16 | public static void main(String[] args) { 17 | 18 | // Start the JavaFX application by calling launch(). 19 | launch(args); 20 | } 21 | 22 | // Override the start() method. 23 | public void start(Stage myStage) { 24 | 25 | // Give the stage a title. 26 | myStage.setTitle("Demonstrate Menus"); 27 | 28 | // Use a BorderPane for the root node. 29 | BorderPane rootNode = new BorderPane(); 30 | 31 | // Create a scene. 32 | Scene myScene = new Scene(rootNode, 300, 300); 33 | 34 | // Set the scene on the stage. 35 | myStage.setScene(myScene); 36 | 37 | // Create a label that will report the selection. 38 | response = new Label("Menu Demo"); 39 | 40 | // Create the menu bar. 41 | MenuBar mb = new MenuBar(); 42 | 43 | // Create the File menu. 44 | Menu fileMenu = new Menu("File"); 45 | MenuItem open = new MenuItem("Open"); 46 | MenuItem close = new MenuItem("Close"); 47 | MenuItem save = new MenuItem("Save"); 48 | MenuItem exit = new MenuItem("Exit"); 49 | fileMenu.getItems().addAll(open, close, save, 50 | new SeparatorMenuItem(), exit); 51 | 52 | // Add File menu to the menu bar. 53 | mb.getMenus().add(fileMenu); 54 | 55 | // Create the Options menu. 56 | Menu optionsMenu = new Menu("Options"); 57 | 58 | // Create the Colors submenu. 59 | Menu colorsMenu = new Menu("Colors"); 60 | MenuItem red = new MenuItem("Red"); 61 | MenuItem green = new MenuItem("Green"); 62 | MenuItem blue = new MenuItem("Blue"); 63 | colorsMenu.getItems().addAll(red, green, blue); 64 | optionsMenu.getItems().add(colorsMenu); 65 | 66 | // Create the Priority submenu. 67 | Menu priorityMenu = new Menu("Priority"); 68 | MenuItem high = new MenuItem("High"); 69 | MenuItem low = new MenuItem("Low"); 70 | priorityMenu.getItems().addAll(high, low); 71 | optionsMenu.getItems().add(priorityMenu); 72 | 73 | // Add a separator. 74 | optionsMenu.getItems().add(new SeparatorMenuItem()); 75 | 76 | // Create the Reset menu item. 77 | MenuItem reset = new MenuItem("Reset"); 78 | optionsMenu.getItems().add(reset); 79 | 80 | // Add Options menu to the menu bar. 81 | mb.getMenus().add(optionsMenu); 82 | 83 | // Create the Help menu. 84 | Menu helpMenu = new Menu("Help"); 85 | MenuItem about = new MenuItem("About"); 86 | helpMenu.getItems().add(about); 87 | 88 | // Add Help menu to the menu bar. 89 | mb.getMenus().add(helpMenu); 90 | 91 | // Create one event handler that will handle menu action events. 92 | EventHandler MEHandler = 93 | new EventHandler() { 94 | public void handle(ActionEvent ae) { 95 | String name = ((MenuItem)ae.getTarget()).getText(); 96 | 97 | // If Exit is chosen, the program is terminated. 98 | if(name.equals("Exit")) Platform.exit(); 99 | 100 | response.setText( name + " selected"); 101 | } 102 | }; 103 | 104 | // Set action event handlers for the menu items. 105 | open.setOnAction(MEHandler); 106 | close.setOnAction(MEHandler); 107 | save.setOnAction(MEHandler); 108 | exit.setOnAction(MEHandler); 109 | red.setOnAction(MEHandler); 110 | green.setOnAction(MEHandler); 111 | blue.setOnAction(MEHandler); 112 | high.setOnAction(MEHandler); 113 | low.setOnAction(MEHandler); 114 | reset.setOnAction(MEHandler); 115 | about.setOnAction(MEHandler); 116 | 117 | // Add the menu bar to the top of the border pane and 118 | // the response label to the center position. 119 | rootNode.setTop(mb); 120 | rootNode.setCenter(response); 121 | 122 | // Show the stage and its scene. 123 | myStage.show(); 124 | } 125 | } 126 | 127 | listing 2 128 | // Add keyboard accelerators for the File menu. 129 | open.setAccelerator(KeyCombination.keyCombination("shortcut+O")); 130 | close.setAccelerator(KeyCombination.keyCombination("shortcut+C")); 131 | save.setAccelerator(KeyCombination.keyCombination("shortcut+S")); 132 | exit.setAccelerator(KeyCombination.keyCombination("shortcut+E")); 133 | 134 | listing 3 135 | // Create the Options menu. 136 | Menu optionsMenu = new Menu("Options"); 137 | 138 | // Create the Colors submenu. 139 | Menu colorsMenu = new Menu("Colors"); 140 | 141 | // Use check menu items for colors. This allows 142 | // the user to select more than one color. 143 | CheckMenuItem red = new CheckMenuItem("Red"); 144 | CheckMenuItem green = new CheckMenuItem("Green"); 145 | CheckMenuItem blue = new CheckMenuItem("Blue"); 146 | colorsMenu.getItems().addAll(red, green, blue); 147 | optionsMenu.getItems().add(colorsMenu); 148 | 149 | // Select green for the default color selection. 150 | green.setSelected(true); 151 | 152 | // Create the Priority submenu. 153 | Menu priorityMenu = new Menu("Priority"); 154 | 155 | // Use radio menu items for the priority setting. 156 | // This lets the menu show which priority is used 157 | // and also ensures that one and only one priority 158 | // can be selected at any one time. 159 | RadioMenuItem high = new RadioMenuItem("High"); 160 | RadioMenuItem low = new RadioMenuItem("Low"); 161 | 162 | // Create a toggle group and use it for the radio menu items. 163 | ToggleGroup tg = new ToggleGroup(); 164 | high.setToggleGroup(tg); 165 | low.setToggleGroup(tg); 166 | 167 | // Select High priority for the default selection. 168 | high.setSelected(true); 169 | 170 | // Add the radio menu items to the priority menu and 171 | // add the priority menu to the options menu. 172 | priorityMenu.getItems().addAll(high, low); 173 | optionsMenu.getItems().add(priorityMenu); 174 | 175 | // Add a separator. 176 | optionsMenu.getItems().add(new SeparatorMenuItem()); 177 | 178 | // Create the Reset menu item. 179 | MenuItem reset = new MenuItem("Reset"); 180 | optionsMenu.getItems().add(reset); 181 | 182 | // Add Options menu to the menu bar. 183 | mb.getMenus().add(optionsMenu); 184 | 185 | listing 4 186 | // Add the context menu to the entire scene graph. 187 | rootNode.setOnContextMenuRequested( 188 | new EventHandler() { 189 | public void handle(ContextMenuEvent ae) { 190 | // Popup menu at the location of the right click. 191 | editMenu.show(rootNode, ae.getScreenX(), ae.getScreenY()); 192 | } 193 | }); 194 | 195 | listing 5 196 | // Define a tool bar. First, create tool bar items. 197 | Button btnSet = new Button("Set Breakpoint", 198 | new ImageView("setBP.gif")); 199 | Button btnClear = new Button("Clear Breakpoint", 200 | new ImageView("clearBP.gif")); 201 | Button btnResume = new Button("Resume Execution", 202 | new ImageView("resume.gif")); 203 | 204 | // Now, turn off text in the buttons. 205 | btnSet.setContentDisplay(ContentDisplay.GRAPHIC_ONLY); 206 | btnClear.setContentDisplay(ContentDisplay.GRAPHIC_ONLY); 207 | btnResume.setContentDisplay(ContentDisplay.GRAPHIC_ONLY); 208 | 209 | // Set tooltips. 210 | btnSet.setTooltip(new Tooltip("Set a breakpoint.")); 211 | btnClear.setTooltip(new Tooltip("Clear a breakpoint.")); 212 | btnResume.setTooltip(new Tooltip("Resume execution.")); 213 | 214 | // Create the tool bar. 215 | ToolBar tbDebug = new ToolBar(btnSet, btnClear, btnResume); 216 | 217 | listing 6 218 | // Create a handler for the tool bar buttons. 219 | EventHandler btnHandler = new EventHandler() { 220 | public void handle(ActionEvent ae) { 221 | response.setText(((Button)ae.getTarget()).getText()); 222 | } 223 | }; 224 | 225 | // Set the tool bar button action event handlers. 226 | btnSet.setOnAction(btnHandler); 227 | btnClear.setOnAction(btnHandler); 228 | btnResume.setOnAction(btnHandler); 229 | 230 | listing 7 231 | // Demonstrate Menus -- Final Version 232 | 233 | import javafx.application.*; 234 | import javafx.scene.*; 235 | import javafx.stage.*; 236 | import javafx.scene.layout.*; 237 | import javafx.scene.control.*; 238 | import javafx.event.*; 239 | import javafx.geometry.*; 240 | import javafx.scene.input.*; 241 | import javafx.scene.image.*; 242 | import javafx.beans.value.*; 243 | 244 | public class MenuDemoFinal extends Application { 245 | 246 | MenuBar mb; 247 | EventHandler MEHandler; 248 | ContextMenu editMenu; 249 | ToolBar tbDebug; 250 | 251 | Label response; 252 | 253 | public static void main(String[] args) { 254 | 255 | // Start the JavaFX application by calling launch(). 256 | launch(args); 257 | } 258 | 259 | // Override the start() method. 260 | public void start(Stage myStage) { 261 | 262 | // Give the stage a title. 263 | myStage.setTitle("Demonstrate Menus -- Final Version"); 264 | 265 | // Use a BorderPane for the root node. 266 | final BorderPane rootNode = new BorderPane(); 267 | 268 | // Create a scene. 269 | Scene myScene = new Scene(rootNode, 300, 300); 270 | 271 | // Set the scene on the stage. 272 | myStage.setScene(myScene); 273 | 274 | // Create a label that will report the selection. 275 | response = new Label(); 276 | 277 | // Create one event handler for all menu action events. 278 | MEHandler = new EventHandler() { 279 | public void handle(ActionEvent ae) { 280 | String name = ((MenuItem)ae.getTarget()).getText(); 281 | 282 | if(name.equals("Exit")) Platform.exit(); 283 | 284 | response.setText( name + " selected"); 285 | } 286 | }; 287 | 288 | // Create the menu bar. 289 | mb = new MenuBar(); 290 | 291 | // Create the File menu. 292 | makeFileMenu(); 293 | 294 | // Create the Options menu. 295 | makeOptionsMenu(); 296 | 297 | // Create the Help menu. 298 | makeHelpMenu(); 299 | 300 | // Create the context menu. 301 | makeContextMenu(); 302 | 303 | // Create a text field and set its column width to 20. 304 | TextField tf = new TextField(); 305 | tf.setPrefColumnCount(20); 306 | 307 | // Add the context menu to the textfield. 308 | tf.setContextMenu(editMenu); 309 | 310 | // Create the tool bar. 311 | makeToolBar(); 312 | 313 | // Add the context menu to the entire scene graph. 314 | rootNode.setOnContextMenuRequested( 315 | new EventHandler() { 316 | public void handle(ContextMenuEvent ae) { 317 | // Popup menu at the location of the right click. 318 | editMenu.show(rootNode, ae.getScreenX(), ae.getScreenY()); 319 | } 320 | }); 321 | 322 | // Add the menu bar to the top of the border pane. 323 | rootNode.setTop(mb); 324 | 325 | // Create a flow pane that will hold both the response 326 | // label and the text field. 327 | FlowPane fpRoot = new FlowPane(10, 10); 328 | 329 | // Center the controls in the scene. 330 | fpRoot.setAlignment(Pos.CENTER); 331 | 332 | // Use a separator to better organize the layout. 333 | Separator separator = new Separator(); 334 | separator.setPrefWidth(260); 335 | 336 | // Add the label, separator, and text field to the flow pane. 337 | fpRoot.getChildren().addAll(response, separator, tf); 338 | 339 | // Add the tool bar to the bottom of the border pane. 340 | rootNode.setBottom(tbDebug); 341 | 342 | // Add the flow pane to the center of the border layout. 343 | rootNode.setCenter(fpRoot); 344 | 345 | // Show the stage and its scene. 346 | myStage.show(); 347 | } 348 | 349 | // Create the File menu. 350 | void makeFileMenu() { 351 | // Create the File menu, including a mnemonic. 352 | Menu fileMenu = new Menu("_File"); 353 | 354 | // Create the File menu items. 355 | MenuItem open = new MenuItem("Open"); 356 | MenuItem close = new MenuItem("Close"); 357 | MenuItem save = new MenuItem("Save"); 358 | MenuItem exit = new MenuItem("Exit"); 359 | 360 | // Add items to File menu. 361 | fileMenu.getItems().addAll(open, close, save, 362 | new SeparatorMenuItem(), exit); 363 | 364 | // Add keyboard accelerators for the File menu. 365 | open.setAccelerator(KeyCombination.keyCombination("shortcut+O")); 366 | close.setAccelerator(KeyCombination.keyCombination("shortcut+C")); 367 | save.setAccelerator(KeyCombination.keyCombination("shortcut+S")); 368 | exit.setAccelerator(KeyCombination.keyCombination("shortcut+E")); 369 | 370 | // Set action event handlers. 371 | open.setOnAction(MEHandler); 372 | close.setOnAction(MEHandler); 373 | save.setOnAction(MEHandler); 374 | exit.setOnAction(MEHandler); 375 | 376 | // Add File menu to the menu bar. 377 | mb.getMenus().add(fileMenu); 378 | } 379 | 380 | // Create the Options menu. 381 | void makeOptionsMenu() { 382 | Menu optionsMenu = new Menu("Options"); 383 | 384 | // Create the Colors submenu. 385 | Menu colorsMenu = new Menu("Colors"); 386 | 387 | // Use check boxes for colors. This allows 388 | // the user to select more than one color. 389 | CheckMenuItem red = new CheckMenuItem("Red"); 390 | CheckMenuItem green = new CheckMenuItem("Green"); 391 | CheckMenuItem blue = new CheckMenuItem("Blue"); 392 | 393 | // Add the check menu items for the colors menu and 394 | // add the colors menu to the options menu. 395 | colorsMenu.getItems().addAll(red, green, blue); 396 | optionsMenu.getItems().add(colorsMenu); 397 | 398 | // Select green for the default color selection. 399 | green.setSelected(true); 400 | 401 | // Create the Priority submenu. 402 | Menu priorityMenu = new Menu("Priority"); 403 | 404 | // Use radio menu items for the priority setting. 405 | // This lets the menu show which priority is used 406 | // and also ensures that one and only one priority 407 | // can be selected at any one time. 408 | RadioMenuItem high = new RadioMenuItem("High"); 409 | RadioMenuItem low = new RadioMenuItem("Low"); 410 | 411 | // Create a toggle group and use it for the radio menu items. 412 | ToggleGroup tg = new ToggleGroup(); 413 | high.setToggleGroup(tg); 414 | low.setToggleGroup(tg); 415 | 416 | // Select High priority for the default selection. 417 | high.setSelected(true); 418 | 419 | // Add the radio menu items to the priority menu and 420 | // add the priority menu to the options menu. 421 | priorityMenu.getItems().addAll(high, low); 422 | optionsMenu.getItems().add(priorityMenu); 423 | 424 | // Add a separator. 425 | optionsMenu.getItems().add(new SeparatorMenuItem()); 426 | 427 | // Create the Reset menu item and add it to the optios menu. 428 | MenuItem reset = new MenuItem("Reset"); 429 | optionsMenu.getItems().add(reset); 430 | 431 | // Set action event handlers. 432 | red.setOnAction(MEHandler); 433 | green.setOnAction(MEHandler); 434 | blue.setOnAction(MEHandler); 435 | high.setOnAction(MEHandler); 436 | low.setOnAction(MEHandler); 437 | reset.setOnAction(MEHandler); 438 | 439 | // Use a change listener to respond to changes in the radio 440 | // menu item setting. 441 | tg.selectedToggleProperty().addListener(new ChangeListener() { 442 | public void changed(ObservableValue changed, 443 | Toggle oldVal, Toggle newVal) { 444 | if(newVal==null) return; 445 | 446 | // Cast newVal to RadioButton. 447 | RadioMenuItem rmi = (RadioMenuItem) newVal; 448 | 449 | // Display the selection. 450 | response.setText("Priority selected is " + rmi.getText()); 451 | } 452 | }); 453 | 454 | // Add Options menu to the menu bar. 455 | mb.getMenus().add(optionsMenu); 456 | } 457 | 458 | // Create the Help menu. 459 | void makeHelpMenu() { 460 | 461 | // Create an ImageView for the image. 462 | ImageView aboutIV = new ImageView("aboutIcon.gif"); 463 | 464 | // Create the help menu. 465 | Menu helpMenu = new Menu("Help"); 466 | 467 | // Create the About menu item and add it to the help menu. 468 | MenuItem about = new MenuItem("About", aboutIV); 469 | helpMenu.getItems().add(about); 470 | 471 | // Set action event handler. 472 | about.setOnAction(MEHandler); 473 | 474 | // Add Help menu to the menu bar. 475 | mb.getMenus().add(helpMenu); 476 | } 477 | 478 | // Create the context menu items. 479 | void makeContextMenu() { 480 | 481 | // Create the edit context menu items. 482 | MenuItem cut = new MenuItem("Cut"); 483 | MenuItem copy = new MenuItem("Copy"); 484 | MenuItem paste = new MenuItem("Paste"); 485 | 486 | // Create a context (i.e., popup) menu that shows edit options. 487 | editMenu = new ContextMenu(cut, copy, paste); 488 | 489 | // Set the action event handlers. 490 | cut.setOnAction(MEHandler); 491 | copy.setOnAction(MEHandler); 492 | paste.setOnAction(MEHandler); 493 | } 494 | 495 | // Create the tool bar. 496 | void makeToolBar() { 497 | // Create tool bar items. 498 | Button btnSet = new Button("Set Breakpoint", 499 | new ImageView("setBP.gif")); 500 | Button btnClear = new Button("Clear Breakpoint", 501 | new ImageView("clearBP.gif")); 502 | Button btnResume = new Button("Resume Execution", 503 | new ImageView("resume.gif")); 504 | 505 | // Turn off text in the buttons. 506 | btnSet.setContentDisplay(ContentDisplay.GRAPHIC_ONLY); 507 | btnClear.setContentDisplay(ContentDisplay.GRAPHIC_ONLY); 508 | btnResume.setContentDisplay(ContentDisplay.GRAPHIC_ONLY); 509 | 510 | // Set tooltips. 511 | btnSet.setTooltip(new Tooltip("Set a breakpoint.")); 512 | btnClear.setTooltip(new Tooltip("Clear a breakpoint.")); 513 | btnResume.setTooltip(new Tooltip("Resume execution.")); 514 | 515 | // Create the tool bar. 516 | tbDebug = new ToolBar(btnSet, btnClear, btnResume); 517 | 518 | // Create a handler for the tool bar buttons. 519 | EventHandler btnHandler = new EventHandler() { 520 | public void handle(ActionEvent ae) { 521 | response.setText(((Button)ae.getTarget()).getText()); 522 | } 523 | }; 524 | 525 | // Set the tool bar button action event handlers. 526 | btnSet.setOnAction(btnHandler); 527 | btnClear.setOnAction(btnHandler); 528 | btnResume.setOnAction(btnHandler); 529 | } 530 | } 531 | 532 | --------------------------------------------------------------------------------