1.01k likes | 1.29k Views
Chapter 27 – Bonus Chapter: Introduction to Java 2 Programming.
E N D
Chapter 27 – Bonus Chapter: Introduction to Java 2 Programming Outline27.1 Introduction27.2 Java Keywords, Primitive Data Types and Class Libraries27.3 Command-Line Java Applications 27.3.1 Printing a Line of Text at the Command-Line 27.3.2 Using a Dialog Box from a Command-Line Application 27.3.3 Another Java Application: Adding Integers27.4 Arrays27.5 Class Vector27.6 Graphical User Interfaces: A Windowed Application withJframes and Event Handling27.7 Graphical User Interfaces: Event Handling with Inner Classes27.8 Graphical User Interfaces: Miscellaneous Components 27.8.1 Class JComboBox 27.8.2 Jlist
Chapter 27 – Bonus Chapter: Introduction to Java 2 Programming Outline27.9 Graphical User Interfaces: Layout Managers 27.9.1 BorderLayout 27.9.2 GridLayout27.10 Graphical User Interfaces: Customizing a Component and Introducing Graphics27.11 Multithreading 27.11.1 Class Thread: An Overview of the Thread Methods 27.11.2 Thread States: Life Cycle of a Thread 27.11.3 Thread Priorities and Thread Scheduling 27.11.4 Creating Threads in an Application27.12 Networking with Sockets and Streams 27.12.1 Establishing a Simple Server (Using Stream Sockets) 27.12.2 Establishing a Simple Client (Using Stream Sockets) 27.12.3 Client/Server Interaction with Stream Socket Connections
Chapter 27 – Bonus Chapter: Introduction to Java 2 Programming Outline27.13 Enhancing a Web Server with Servlets 27.13.1 Overview of Servlet Technology 27.13.2 The Servlet API 27.13.3 HttpServlet Class 27.13.4 HttpServletRequest Interface 27.13.5 HttpServletResponse Interface 27.13.6 Multi-tier Client/Server Application with Servlets
27.1 Introduction • Java 2 Platform • Object-oriented language • Used for building substantial information systems
27.2 Java Keywords, Primitive Data Types and Class Libraries • Java keywords • Reserved words for use by Java • Should not be used as identifiers • Primitive data types • Fundamental building block of all types in Java • Java has eight primitive data types • Class libraries • Sets of reusable components • Used to build programs rapidly and reliably • Organized into packages of related classes and interfaces
27.3 Command-Line Java Applications • Command-line Java applications • Execute from command prompt • Windows, Unix/Linux shell
27.3.1 Printing a Line of Text at the Command Line • Java application • Displays line of text in command prompt (shell)
Single-line comments begin with // and are ignored by compiler Class definition (every Java program must have at least one) Curly braces {} indicate body mainmethod starts application Print line of text to screen 1 // Fig. 27.5: Welcome1.java 2 // A first program in Java 3 4 public class Welcome1 { 5 publicstaticvoid main( String args[] ) 6 { 7 System.out.println( "Welcome to Java Programming!" ); 8 } 9 } Fig. 27.5 A first program in Java.Lines 1-2Line 4Lines 4 and 9Line 5Line 7Output Welcome to Java Programming!
Fig. 27.6 Executing the Welcome1 application in a Microsoft Windows 2000 CommandPrompt
27.3.2 Using a Dialog Box from a Command-Line Application • Most Java applications use windows • Dialog boxes display output • e.g., Netscape Communicator or Microsoft Internet Explorer
Import JOptionPane from javax.swing package Method showMessageDialog of class JOptionPane displays text in dialog box Method exit of class System terminates program 1 // Fig. 27.7: Welcome2.java 2 // Printing multiple lines in a dialog box 3 import javax.swing.JOptionPane; // import class JOptionPane 4 5 publicclass Welcome2 { 6 publicstaticvoid main( String args[] ) 7 { 8 JOptionPane.showMessageDialog( 9 null, "Welcome\nto\nJava\nProgramming!" ); 10 11 System.exit( 0 ); // terminate the program 12 } 13 } Fig. 27.7 Displaying multiple lines in a dialog box.Line 1Lines 8-9Line 11Output
Fig. 27.8 A sample Internet Explorer window with GUI components.
Title bar The dialog box isautomatically sizedto accommodate thestring. The OK buttonallows the userto dismiss thedialog box. Mouse cursor Fig. 27.9 Dialog box produced by the program of Fig. 27.7.
27.3.3 Another Java Application: Adding Integers • Java application that adds integers • User inputs two integers via keyboard • (User inputs two Strings that are converted to ints) • Application computes sum of integers • Application displays result
Specify where to locate class JOptionPane Declare two String variables to hold first and second user-specified Strings, respectively Declare three int variables to hold two numbers and their sum Receive user input Use static method parseInt of class Integer to convert Strings to ints Compute and display sum 1 // Fig. 27.10: Addition.java 2 // An addition program 3 4 import javax.swing.JOptionPane; // import class JOptionPane 5 6 publicclass Addition { 7 publicstaticvoid main( String args[] ) 8 { 9 String firstNumber, // first string entered by user 10 secondNumber; // second string entered by user 11 int number1, // first number to add 12 number2, // second number to add 13 sum; // sum of number1 and number2 14 15 // read in first number from user as a string 16 firstNumber = 17 JOptionPane.showInputDialog( "Enter first integer" ); 18 19 // read in second number from user as a string 20 secondNumber = 21 JOptionPane.showInputDialog( "Enter second integer" ); 22 23 // convert numbers from type String to type int 24 number1 = Integer.parseInt( firstNumber ); 25 number2 = Integer.parseInt( secondNumber ); 26 27 // add the numbers 28 sum = number1 + number2; 29 30 // display the results 31 JOptionPane.showMessageDialog( 32 null, "The sum is " + sum, "Results", 33 JOptionPane.PLAIN_MESSAGE ); Fig. 27.10 An addition program “in action.”Line 4Lines 9-10Lines 11-13Lines 16-21Lines 24-25Lines 28-33
34 35 System.exit( 0 ); // terminate the program 36 } 37 } Fig. 27.10 An addition program “in action” (Part 2).
This is the prompt to the user. When the user clicks OK, the 45 typed by the user is returned to the program as a String. The program must convert String to a number. This is the text field in which the user types thevalue. Fig. 27.11 Input dialog displayed to input a value from the user of Fig. 27.10.
Argument 2: The messageto display Argument 3: Thetitle bar string The user clicks OKto dismiss the dialog Fig. 27.12 Message dialog displayed by the program of Fig. 27.10.
27.4 Arrays • Arrays • Data structure consisting of related data items of same type • Static entities • Remain same size once created • Group of contiguous memory locations • All have same name and type • Contain subscripts • Also called an indices • Position number in square brackets • Must be integer or integer expression
27.4 Arrays (cont.) • Declaring and Allocating arrays • Arrays are objects that occupy memory • Allocated dynamically with operator new int c[] = newint[ 12 ]; • Equivalent toint c[]; // declare array c = newint[ 12 ]; // allocate array • We can allocate arrays of objects too String b[] = new String[ 100 ];
Declare n as an array of ints Allocate 10ints for n; each int is initialized to 0 by default n.length returns length of n n[i] returns int associated with index in n 1 // Fig. 27.14: InitArray.java 2 // initializing an array 3 import javax.swing.*; 4 5 publicclass InitArray { 6 publicstatic void main( String args[] ) 7 { 8 String output = ""; 9 int n[]; // declare reference to an array 10 11 n = newint[ 10 ]; // dynamically allocate array 12 13 output += "Subscript\tValue\n"; 14 15 for ( int i = 0; i < n.length; i++ ) 16 output += i + "\t" + n[ i ] + "\n"; 17 18 JTextArea outputArea = new JTextArea( 11, 10 ); 19 outputArea.setText( output ); 20 21 JOptionPane.showMessageDialog( null, outputArea, 22 "Initializing an Array of int Values", 23 JOptionPane.INFORMATION_MESSAGE ); 24 25 System.exit( 0 ); 26 } 27 } Fig. 27.14 Initializing the elements of an array to zeros.Line 9Line 11Line 15Line 16
Each int is initialized to 0 by default Output of Fig. 27.14 Each int is initialized to 0 by default
Declare n as an array of ints Compiler uses initializer list to allocate array 1 // Fig. 27.15: InitArray2.java 2 // initializing an array with a declaration 3 import javax.swing.*; 4 5 public class InitArray2 { 6 public static void main( String args[] ) 7 { 8 String output = ""; 9 10 // Initializer list specifies number of elements and 11 // value for each element. 12 int n[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; 13 14 output += "Subscript\tValue\n"; 15 16 for ( int i = 0; i < n.length; i++ ) 17 output += i + "\t" + n[ i ] + "\n"; 18 19 JTextArea outputArea = new JTextArea(); 20 outputArea.setText( output ); 21 22 JOptionPane.showMessageDialog( null, outputArea, 23 "Initializing an Array with a Declaration", 24 JOptionPane.INFORMATION_MESSAGE ); 25 26 System.exit( 0 ); 27 } 28 } Fig. 27.15 Initializing the elements of an array with a declaration.Line 12Line 12
Each n element corresponds to element in initializer list Output of Fig. 27.15 Each n element corresponds to element in initializer list
27.5 Class Vector • Class java.util.Vector • Dynamically resizable array-like data structure
Declare v as Vector Method addElement adds Objects to Vector (Vector grows dynamically to accommodate Objects) 1 // Fig. 27.16: VectorDemo.java 2 // This program demonstrates class Vector. 3 import javax.swing.*; 4 import java.util.*; 5 6 publicclass VectorDemo { 7 public static void main( String args[] ) 8 { 9 Vector v = new Vector(); 10 Object o = "hello!"; 11 String s = "good bye"; 12 13 v.addElement( o ); 14 v.addElement( s ); 15 v.addElement( new Boolean( true ) ); 16 v.addElement( new Character( 'Z' ) ); 17 v.addElement( new Integer( 7 ) ); 18 v.addElement( new Long( 10000000 ) ); 19 v.addElement( new Float( 2.5f ) ); 20 v.addElement( new Double( 3.333 ) ); 21 22 System.out.println( "Vector v contains:" ); 23 24 for ( int j = 0; j < v.size(); j++ ) 25 System.out.print( v.elementAt( j ) ); 26 } 27 } Fig. 27.16 Class Vector.Line 9Lines 13-20 Vector v contains: hello!good byetrueZ7100000002.53.333
27.6 Graphical User Interfaces: A Windowed Application with JFrames and Event Handling • Windowed application • Use class java.swing.JFrame • Contains GUI components • Use java.util.StringTokenizer • Parses Strings
Interface ActionListener specifies that class TokenTest must define method actionPerformed input contains String to be parsed by StringTokenizer 1 // Fig. 27.17: TokenTest.java 2 // Testing the StringTokenizer class of the java.util package. 3 import javax.swing.*; 4 import java.util.*; 5 import java.awt.*; 6 import java.awt.event.*; 7 8 public class TokenTest extends JFrame 9 implements ActionListener { 10 private JLabel prompt; 11 private JTextField input; 12 private JTextArea output; 13 14 public TokenTest() 15 { 16 super( "Testing Class StringTokenizer" ); 17 18 Container c = getContentPane(); 19 c.setLayout( new FlowLayout() ); 20 21 prompt = new JLabel( "Enter a sentence and press Enter" ); 22 c.add( prompt ); 23 24 input = new JTextField( 25 ); 25 c.add( input ); 26 input.addActionListener( this ); 27 28 output = new JTextArea( 10, 25 ); 29 output.setEditable( false ); 30 c.add( new JScrollPane( output ) ); 31 32 setSize( 300, 260 ); // set the window size 33 show(); // show the window 34 } 35 Fig. 27.17 A JFrame-based windows application with event handling.Line 9Line 24
When user clicks JButton, method actionPerformed is invoked Use StringTokenizer to parse StringstringToTokenize with default delimiter “ \n\t\r” Count number of tokens Append next token to output, as long as tokens exist 36 public void actionPerformed( ActionEvent e ) 37 { 38 String stringToTokenize = e.getActionCommand(); 39 StringTokenizer tokens = 40 new StringTokenizer( stringToTokenize ); 41 42 output.setText( "Number of elements: " + 43 tokens.countTokens() + "\nThe tokens are:\n" ); 44 45 while ( tokens.hasMoreTokens() ) 46 output.append( tokens.nextToken() + "\n" ); 47 } 48 49 // Method main to begin program execution by creating an 50 // object of class TokenTest. 51 public static void main( String args[] ) 52 { 53 TokenTest app = new TokenTest(); 54 55 app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 56 } 57 } Fig. 27.17 A JFrame-based windows application with event handling (Part 2).Lines 36-47Lines 39-40Line 43Lines 45-46Output
27.7 Graphical User Interfaces: Event Handling with Inner Classes • Inner classes • Classes can be defined in other classes • Anonymous inner classes • Inner classes without names • Demonstrate with Time application • Allow user to set time by specifying hour, minute and second
Time (subclass) inherits superclass java.lang.Object private variables (and methods) are accessible only to methods in this class public methods (and variables) are accessible wherever program has Time reference Time constructor creates Time object then invokes method setTime Method setTime calls methods setHour, setMinute and setSecond to set private variables according to arguments Mutator methods allows objects to manipulate private variables 1 // Fig. 27.18: Time.java 2 // Time class definition 3 import java.text.DecimalFormat; // used for number formatting 4 5 // This class maintains the time in 24-hour format 6 public class Time extends Object { 7 private int hour; // 0 - 23 8 private int minute; // 0 - 59 9 private int second; // 0 - 59 10 11 // Time constructor initializes each instance variable 12 // to zero. Ensures that Time object starts in a 13 // consistent state. 14 public Time() { setTime( 0, 0, 0 ); } 15 16 // Set a new time value using universal time. Perform 17 // validity checks on the data. Set invalid values to zero. 18 public void setTime( int h, int m, int s ) 19 { 20 setHour( h ); // set the hour 21 setMinute( m ); // set the minute 22 setSecond( s ); // set the second 23 } 24 25 // set the hour 26 public void setHour( int h ) 27 { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); } 28 29 // set the minute 30 public void setMinute( int m ) 31 { minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); } 32 33 // set the second 34 public void setSecond( int s ) 35 { second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } Fig. 27.18 GUI event handling with inner classes – Time.java.Line 6Lines 7-9Lines 14, 18, 26, 30 and 34Line 14Lines 18-23Lines 26-35
Accessor methods allows objects to access private variables Method toString is a method from java.lang.Object Time1overrides this method to provide more appropriate method Class TimeTestWindow is GUI for application 36 37 // get the hour 38 public int getHour() { return hour; } 39 40 // get the minute 41 public int getMinute() { return minute; } 42 43 // get the second 44 public int getSecond() { return second; } 45 46 // Convert to String in standard-time format 47 public String toString() 48 { 49 DecimalFormat twoDigits = new DecimalFormat( "00" ); 50 51 int h = getHour(); 52 53 return ( ( h == 12 || h == 0 ) ? 12 : h % 12 ) + ":" + 54 twoDigits.format( getMinute() ) + ":" + 55 twoDigits.format( getSecond() ) + 56 ( h < 12 ? " AM" : " PM" ); 57 } 58 } 59 // Fig. 27.18: TimeTestWindow.java 60 // Demonstrating the Time class set and get methods 61 import java.awt.*; 62 import java.awt.event.*; 63 import javax.swing.*; 64 65 public class TimeTestWindow extends JFrame { 66 private Time t; 67 private JLabel hourLabel, minuteLabel, secondLabel; 68 private JTextField hourField, minuteField, 69 secondField, display; 70 Fig. 27.18 GUI event handling with inner classes – Time.java (Part 2).Lines 38-44Line 47Line 47Line 65
Register JTextFieldhourField for events from object of anonymous inner class ActionListener Register JTextFieldminuteField for events from object of anonymous inner class ActionListener 71 public TimeTestWindow() 72 { 73 super( "Inner Class Demonstration" ); 74 75 t = new Time(); 76 77 Container c = getContentPane(); 78 c.setLayout( new FlowLayout() ); 79 80 hourLabel = new JLabel( "Set Hour" ); 81 hourField = new JTextField( 10 ); 82 hourField.addActionListener( 83 new ActionListener() { // anonymous inner class 84 public void actionPerformed( ActionEvent e ) 85 { 86 t.setHour( 87 Integer.parseInt( e.getActionCommand() ) ); 88 hourField.setText( "" ); 89 displayTime(); 90 } 91 } 92 ); 93 c.add( hourLabel ); 94 c.add( hourField ); 95 96 minuteLabel = new JLabel( "Set minute" ); 97 minuteField = new JTextField( 10 ); 98 minuteField.addActionListener( 99 new ActionListener() { // anonymous inner class 100 public void actionPerformed( ActionEvent e ) 101 { 102 t.setMinute( 103 Integer.parseInt( e.getActionCommand() ) ); 104 minuteField.setText( "" ); 105 displayTime(); Fig. 27.18 GUI event handling with inner classes – Time.java (Part 3).Lines 82-92Lines 98-108
Register JTextFieldsecondField for events from object of anonymous inner class ActionListener 106 } 107 } 108 ); 109 c.add( minuteLabel ); 110 c.add( minuteField ); 111 112 secondLabel = new JLabel( "Set Second" ); 113 secondField = new JTextField( 10 ); 114 secondField.addActionListener( 115 new ActionListener() { // anonymous inner class 116 public void actionPerformed( ActionEvent e ) 117 { 118 t.setSecond( 119 Integer.parseInt( e.getActionCommand() ) ); 120 secondField.setText( "" ); 121 displayTime(); 122 } 123 } 124 ); 125 c.add( secondLabel ); 126 c.add( secondField ); 127 128 display = new JTextField( 30 ); 129 display.setEditable( false ); 130 c.add( display ); 131 } 132 133 public void displayTime() 134 { 135 display.setText( "The time is: " + t ); 136 } 137 Fig. 27.18 GUI event handling with inner classes – Time.java (Part 4).Lines 114-124
138 public static void main( String args[] ) 139 { 140 TimeTestWindow window = new TimeTestWindow(); 141 142 window.addWindowListener( 143 new WindowAdapter() { 144 publicvoid windowClosing( WindowEvent e ) 145 { 146 System.exit( 0 ); 147 } 148 } 149 ); 150 151 window.setSize( 400, 120 ); 152 window.show(); 153 } 154 } Fig. 27.18 GUI event handling with inner classes – Time.java (Part 5).
Fig. 27.18 GUI event handling with inner classes – Time.java (Part 6).
27.8 Graphical User Interfaces: Miscellaneous Components • java.swing.JComboBox • java.swing.JList
27.8.1 Class JComboBox • JComboBox • List of items from which user can select • Also called a drop-down list
Instantiate JComboBox to show three Strings from names array at a time 1 // Fig. 27.19: ComboBoxTest.java 2 // Using a JComboBox to select an image to display. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class ComboBoxTest extends JFrame { 8 private JComboBox images; 9 private JLabel label; 10 private String names[] = 11 { "bug1.gif", "bug2.gif", 12 "travelbug.gif", "buganim.gif" }; 13 private Icon icons[] = 14 { new ImageIcon( names[ 0 ] ), 15 new ImageIcon( names[ 1 ] ), 16 new ImageIcon( names[ 2 ] ), 17 new ImageIcon( names[ 3 ] ) }; 18 19 public ComboBoxTest() 20 { 21 super( "Testing JComboBox" ); 22 23 Container c = getContentPane(); 24 c.setLayout( new FlowLayout() ); 25 26 images = new JComboBox( names ); 27 images.setMaximumRowCount( 3 ); 28 Fig. 27.19 Program that uses a JComboBox to select and icon.Lines 26-27
Register JComboBox to receive events from anonymous ActionListener When user selects item in JComboBox, ActionListener invokes method actionPerformed of all registered listeners Set appropriate Icon depending on user selection 29 images.addActionListener( 30 new ActionListener() { 31 public void actionPerformed( ActionEvent e ) 32 { 33 label.setIcon( 34 icons[ images.getSelectedIndex() ] ); 35 } 36 } 37 ); 38 39 c.add( images ); 40 41 label = new JLabel( icons[ 0 ] ); 42 c.add( label ); 43 44 setSize( 350, 100 ); 45 show(); 46 } 47 48 public static void main( String args[] ) 49 { 50 ComboBoxTest app = new ComboBoxTest(); 51 52 app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 53 } 54 } Fig. 27.19 Program that uses a JComboBox to select and icon (Part 2).Line 29Lines 31-35Lines 33-34
27.8.2 JList • List • Series of items • User can select one or more items • Single-selection vs. multiple-selection • JList
Use colorNames array to populate JList 1 // Fig. 27.20: ListTest.java 2 // Selecting colors from a JList. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 import javax.swing.event.*; 7 8 public class ListTest extends JFrame { 9 private JList colorList; 10 private Container c; 11 12 private String colorNames[] = 13 { "Black", "Blue", "Cyan", "Dark Gray", "Gray", "Green", 14 "Light Gray", "Magenta", "Orange", "Pink", "Red", 15 "White", "Yellow" }; 16 17 private Color colors[] = 18 { Color.black, Color.blue, Color.cyan, Color.darkGray, 19 Color.gray, Color.green, Color.lightGray, 20 Color.magenta, Color.orange, Color.pink, Color.red, 21 Color.white, Color.yellow }; 22 23 public ListTest() 24 { 25 super( "List Test" ); 26 27 c = getContentPane(); 28 c.setLayout( new FlowLayout() ); 29 30 // create a list with the items in the colorNames array 31 colorList = new JList( colorNames ); 32 colorList.setVisibleRowCount( 5 ); 33 34 // do not allow multiple selections 35 colorList.setSelectionMode( Fig. 27.20 Selecting colors from a JList.Line 34
JList allows single selections Register JList to receive events from anonymous ListSelectionListener When user selects item in JList, ListSelectionListener invokes method valueChanged of all registered listeners Set appropriate background depending on user selection 36 ListSelectionModel.SINGLE_SELECTION ); 37 38 // add a JScrollPane containing the JList 39 // to the content pane 40 c.add( new JScrollPane( colorList ) ); 41 42 // set up event handler 43 colorList.addListSelectionListener( 44 new ListSelectionListener() { 45 public void valueChanged( ListSelectionEvent e ) 46 { 47 c.setBackground( 48 colors[ colorList.getSelectedIndex() ] ); 49 } 50 } 51 ); 52 53 setSize( 350, 150 ); 54 show(); 55 } 56 57 public static void main( String args[] ) 58 { 59 ListTest app = new ListTest(); 60 61 app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 62 } 63 } Fig. 27.20 Selecting colors from a JList(Part 2).Lines 35-36Lines 43Lines 45-49Lines 47-48