Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore MCA631_Advanced Internet Programming

MCA631_Advanced Internet Programming

Published by Teamlease Edtech Ltd (Amita Chitroda), 2020-12-05 14:21:54

Description: MCA631_Advanced Internet Programming

Search

Read the Text Version

INSTITUTE OF DISTANCE & ONLINE LEARNING MASTER OF COMPUTER APPLICATIONS ADVANCED INTERNET PROGRAMMING (THEORY AND PRACTICAL) MCA631/MCA636 Self Learning Material R101

MASTER OF COMPUTER APPLICATIONS ADVANCED INTERNET PROGRAMMING (THEORY AND PRACTICAL) MCA631/MCA636 Kiran Gurbani

CHANDIGARH UNIVERSITY Institute of Distance and Online Learning Course Development Committee Chairman Prof. (Dr.) R.S. Bawa Vice Chancellor, Chandigarh University, Punjab Advisors Prof. (Dr.) Bharat Bhushan, Director, IGNOU Prof. (Dr.) Majulika Srivastava, Director, CIQA, IGNOU Programme Coordinators & Editing Team Master of Business Administration (MBA) Bachelor of Business Administration (BBA) Co-ordinator - Prof. Pragya Sharma Co-ordinator - Dr. Rupali Arora Master of Computer Applications (MCA) Bachelor of Computer Applications (BCA) Co-ordinator - Dr. Deepti Rani Sindhu Co-ordinator - Dr. Raju Kumar Master of Commerce (M.Com.) Bachelor of Commerce (B.Com.) Co-ordinator - Dr. Shashi Singhal Co-ordinator - Dr. Minakshi Garg Master of Arts (Psychology) Bachelor of Science (Travel & Tourism Management) Co-ordinator - Ms. Nitya Mahajan Co-ordinator - Dr. Shikha Sharma Master of Arts (English) Bachelor of Arts (General) Co-ordinator - Dr. Ashita Chadha Co-ordinator - Ms. Neeraj Gohlan Master of Arts (Mass Communication and Bachelor of Arts (Mass Communication and Journalism) Journalism) Co-ordinator - Dr. Chanchal Sachdeva Suri Co-ordinator - Dr. Kamaljit Kaur Academic and Administrative Management Prof. (Dr.) Pranveer Singh Satvat Prof. (Dr.) S.S. Sehgal Pro VC (Academic) Registrar Prof. (Dr.) H. Nagaraja Udupa Prof. (Dr.) Shiv Kumar Tripathi Director – (IDOL) Executive Director – USB © No part of this publication should be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording and/or otherwise without the prior written permission of the author and the publisher. SLM SPECIALLY PREPARED FOR CU IDOL STUDENTS Printed and Published by: Himalaya Publishing House Pvt. Ltd., E-mail: himpub@bharatmail.co.in, Website: www.himpub.com For: CHANDIGARH UNIVERSITY Institute of Distance and Online Learning CU IDOL SELF LEARNING MATERIAL (SLM)

Advanced Internet Programming Credits: 3 (Theory and Practical) Course Code: MCA631/ MCA636 Course Objectives:  To provide knowledge of JDBC, and user interface components.  To develop skills related to event handling and Java Servlets.  To inculcate skills related to AJAX. Syllabus Unit 1 - Java Data Base Connectivity: JDBC Configuration, Types of Drivers for connection, CRUD operations, Sequence, Meta Data and Prepared Statement, Callable statement and Transactions. (Database: Oracle, MySQL and PostgreSQL). JDBC Configuration, Types of Drivers for connection, CRUD operations, Sequence, Unit 2 - User Interface Components: MVC Architecture, Layout Manager, Jcomponent class, JButton, JLabel, JText, JTextArea, JCheckBox and JRadioButton, JList, JComboBox, JMenu and JPopupMenu Class, JMenuItem and JCheckBoxMenuItem, JRadioButtonMenuItem, JscrollBar, Dialogs (Message, confirmation, input), JFileChooser, JcolorChooser, Unit 3 - Event Handling: Event sources, Listeners, Mouse and Keyboard Event Handling, Adapters, Swing component and Container class. Unit 4 - Java Servlets 1: Server-Side Programming, Web Server, Java Server side components, Servlet Architecture. Web Container, Servlet Life Cycle, Tomcat Interface, Servlet interface, Unit 5 - Java Servlets 2: Servicing client requests, GET and POST request methods. Retrieving data from database to servlet, Servlet config and Servlet context, Session Tracking. CU IDOL SELF LEARNING MATERIAL (SLM)

Unit 6 - AJAX 1: AJAX architecture, AJAX request & response objects, AJAX Technologies, XMLHttpRequest, AJAX with Database. Unit 7 - AJAX 2: AJAX -PHP framework, Email Finder, Comment form using AJAX in Java, Handling XML data using PHP and AJAX, AJAX JSON. Unit 8 - JSP: JSP: Architecture of JSP, Elements of JSP, Scripting elements, Directives and actions, JSP configuration, White space preservation, implicit objects,Filter, JSP in XML and custom tag libraries. Unit 9 - Java Hibernate: Architecture, Configuration, sessions, persistent class, mapping, O/R mapping, annotation, query languages, criteria queries, Native SQL, caching and interceptor. Unit 10 - Java Struts 1: Environment setup, configuration, actions, interceptors, result types, File uploads, database access, Unit 11 - Java Struts 2: Java Struts 2: Sending mails, validation, localization, type conversion, exception handling, annotation, tags and integrations. Text Books: 1. Schildt,H.(2017).Java: The Complete Reference. Tenth Edition, New Delhi: McGraw-Hill Education. 2. Gavin, K.,Bauer C. (2006).Java Persistence with Hibernate,New York: Manning publisher. Reference Books: 1. Y. D. Liang (2015). Introduction to Java Programming, Delhi: Pearson Education. 2. Jaworski, J. (1999). JAVA 2 Platform Unleashed, New Delhi: Tech Media Publications. 3. JAVA API Documents. CU IDOL SELF LEARNING MATERIAL (SLM)

Advanced Internet Programming Practical Course Code: MCA636 Credits: 1 Course Objectives:  To implement the concepts underlying principles of Advanced Java  To develop and analyze JavaScript programs  To develop and analyze AJAX programs Syllabus Unit 1 - Basics 1. Implementation of CRUD operations on JDBC Applications with Oracle-MySQL- PostgreSQL. 2. Implementation of Java Swings with JDBC Applications with Oracle-MySQL- PostgreSQL. 3. Create Servlet file which contains following functions:  Connect  Create Database  Create Table  Insert Records into respective table  Update records of particular table of database  Delete Records from table.  Delete table and also database. 4. Create login form and perform state management using Cookies, HttpSession and URL Rewriting. 5. Study and Implement MVC using Spring Framework 6. Create database of student subject-wise data and retrieve all data using JSP and generate xml structure along with DTD and XML Schema definition 7. Create a table of the cookies associated with the suitable home page. If there are no active cookies display as stating “No Cookies” otherwise display cookie name and value in a tabular format 8. Create a Servlet that uses session tracking to keep per-client access counts. Also show other generic- info about the session. 9. Make a program which creates a cookie on the server side using servlets & when server returns a response to the user also send cookies to clients for later retrieve its data from that client. CU IDOL SELF LEARNING MATERIAL (SLM)

Unit 2- JavaScript/CSS (a) Create a registration page using HTML and CSS with right corner of the page having current date and time. (b) Design specification for the webpage as follows: (i) The text box background color will be displayed and shadowed when the cursor inserts into the text field. (ii) The text area background color will be displayed and shadowed when the cursor places into textarea. (iii) The submit button background color will be displayed and shadowed when the cursor moves over the submit button. (c) For the same page and write validation function for registration page and modify the on Submit event handler in the form code to validate the following form fields: (i) FirstName 1. Must be entered 2. Must be Character (ii) Password 1. Password length should be between 6 to 20 characters. (iii) Gender(Use radio button) 1. Must be selected (iv) Mobile Number 1. Must be in format(XX-XXXXX-XXXXX) (v) Email 1. Email address must contain at least an @ sign and a dot(.) Unit 3 - Java Server Pages: Experiment: I (i) Create a bean that represents information needed to calculate an employee's salary. Has String (employee name) and int (employee ID) properties. Create an application to demonstrate byautomatically filling in bean properties from request parameters. Experiment: II (ii) Create an emp table in the database with fields name, id and designation. (iii) Create a HTML file with fields name, id and designation. Make sure that the textfields have the same name as name, id and designation. (iv) Create a javabean with fields name, id and designation. (v) On click of the submit button of the HTML, invoke a jsp page which will extract the values that were given by the HTML page and it invokes a servlet. (vi) The Servlet will make a connection to the database and store the value in the table. CU IDOL SELF LEARNING MATERIAL (SLM)

(vii) Connection to the database should have been established using a separate java class. (viii) You can enhance the program by including more features like deletion, updation and selecting all records. Unit 4 -AJAX (A) Develop a web application to dynamically check for availability of an email-id for registration. If email-id does not exist in the database, ‘Available!’, else ‘Not Available!’, should be displayed next to the email textbox. If email-id pattern does not conform to an email-id, display Invalid Email Id. Perform the check when the textbox loses focus. Consider the following fields for the Profile table: EMAIL, PASSWORD, NAME, DATEOFBIRTH, GENDER, CITY, PINCODE, MOBILE Note*: Check should be performed irrespective of uppercase or lowercase data. Text Books: 1. Schildt, H., 2017, “Java: The Complete Reference”. Tenth Edition, New Delhi: McGraw- Hill Education. 2. Gavin, K., Bauer C., 2006, “Java Persistence with Hibernate”, New York: Manning publisher. Reference Books: 1. Y. D. Liang, 2015, “Introduction to Java Programming”, Delhi: Pearson Education. 2. Jaworski, J., 1999, “JAVA 2 Platform Unleashed”, New Delhi: Tech Media Publications. 3. JAVA API Documents. CU IDOL SELF LEARNING MATERIAL (SLM)

CONTENTS 1 - 16 17 - 58 Unit 1: Java Data Base Connectivity 59 - 75 Unit 2: User Interface Components 76 - 91 Unit 3: Event Handling 92 - 113 Unit 4: Java Servlets - I 114 - 130 Unit 5: Java Servlets - II 131 - 141 Unit 6: AJAX - I 142 - 171 Unit 7: AJAX - II 172 - 210 Unit 8: Java Server Pages 211 - 242 Unit 9: Java Hibernate 243 - 285 Unit 10: Java Struts - I 286 - 335 Unit 11: Java Struts - II 336 - 342 343 - 356 Practical Unit 1: Basics 357 - 362 Practical Unit 2: JavaScript/CSS Practical Unit 3: Java Server Pages Practical Unit 4: AJAX CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 1 JAVA DATA BASE CONNECTIVITY Structure: 1.0 Learning Objectives 1.1 Introduction 1.2 What is JDBC? 1.3 JDBC has Four Components 1.4 Layers of the JDBC Architecture 1.5 JDBC Driver 1.6 Java Database Connectivity Steps 1.7 JDBC Statements 1.8 Types of ResultSet 1.9 CRUD operation with Examples 1.10 Practical Assignment 1.11 Summary 1.12 Key Words/Abbreviations 1.13 Learning Activity 1.14 Unit End Questions (MCQs and Descriptive) 1.15 References CU IDOL SELF LEARNING MATERIAL (SLM)

2 Advanced Internet Programming 1.0 Learning Objectives After studying this unit, you will be able to:  Explain the JDBC configurations and types of drivers for connection  Describe CRUD operations  Define meta data and prepared statements  Elaborate callable statement and transactions 1.1 Introduction JDBC stands for Java Database Connectivity, which is a standard Java API for database- independent connectivity between the Java programming language and a wide range of databases. The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database usage.  Making a connection to a database.  Creating SQL or MySQL statements.  Executing SQL or MySQL queries in the database.  Viewing & Modifying the resulting records. 1.2 What is JDBC? JDBC has been developed under the Java Community Process that allows multiple implementations to exist and be used by the same application. JDBC provides methods for querying and updating the data in Relational Database Management system such as SQL, Oracle etc. The Java application programming interface provides a mechanism for dynamically loading the correct Java packages and drivers and registering them with the JDBC Driver Manager that is used as a connection factory for creating JDBC connections which supports creating and executing statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the jdbc architecture. In short JDBC helps the programmers to write java applications that manage these three programming activities: CU IDOL SELF LEARNING MATERIAL (SLM)

Java Data Base Connectivity 3 1. It helps us to connect to a data source, like a database. 2. It helps us in sending queries and updating statements to the database and 3. Retrieving and processing the results received from the database in terms of answering to your query. 1.3 JDBC has Four Components 1. The JDBC API. 2. The JDBC Driver Manager. 3. The JDBC Test Suite. 4. The JDBC-ODBC Bridge. 1. The JDBC API. The JDBC application programming interface provides the facility for accessing the relational database from the Java programming language. The API technology provides the industrial standard for independently connecting Java programming language and a wide range of databases. The user not only execute the SQL statements, retrieve results, and update the data but can also access it anywhere within a network because of it’s “Write Once, Run Anywhere” (WORA) capabilities. Due to JDBC API technology, user can also access other tabular data sources like spreadsheets or flat files even in the heterogeneous environment. JDBC application programming interface is a part of the Java platform that has included Java Standard Edition (Java SE) and the Java Enterprise Edition (Java EE) in itself. The JDBC API has four main interfaces: The latest version of JDBC 4.0 application programming interface is divided into two packages (i) java.sql (ii) javax.sql. Java SE and Java EE platforms are included in both the packages. 2. The JDBC Driver Manager. The JDBC Driver Manager is a very important class that defines objects which connect Java applications to a JDBC driver. Usually Driver Manager is the backbone of the JDBC architecture. CU IDOL SELF LEARNING MATERIAL (SLM)

4 Advanced Internet Programming It’s very simple and small that is used to provide a means of managing the different types of JDBC database driver running on an application. The main responsibility of JDBC database driver is to load all the drivers found in the system properly as well as to select the most appropriate driver from opening a connection to a database. The Driver Manager also helps to select the most appropriate driver from the previously loaded drivers when a new open database is connected. 3. The JDBC Test Suite. The function of JDBC driver test suite is to make ensure that the JDBC drivers will run user’s program or not. The test suite of JDBC application program interface is very useful for testing a driver based on JDBC technology during testing period. It ensures the requirement of Java Platform Enterprise Edition (J2EE). 4. The JDBC-ODBC Bridge. The JDBC-ODBC bridge, also known as JDBC type 1 driver is a database driver that utilizes the ODBC driver to connect the database. This driver translates JDBC method calls into ODBC function calls. The Bridge implements Jdbc for any database for which an Odbc driver is available. The Bridge is always implemented as the sun.jdbc.odbc Java package and it contains a native library used to access ODBC. Now we can conclude this topic: This first two component of JDBC, the JDBC API and the JDBC Driver Manager manages to connect to the database and then build a java program that utilizes SQL commands to communicate with any RDBMS. On the other hand, the last two components are used to communicate with ODBC or to test web application in the specialized environment. JDBC is an API specification developed by Sun Microsystems that defines a uniform interface for accessing various relational databases. JDBC is a core part of the Java platform and is included in the standard JDK distribution. 1.4 Layers of the JDBC Architecture JDBC is a platform-independent interface between relational databases and Java. In today’s Java world, JDBC is a standard application programming interface (API) for accessing enterprise data in relational databases (such as Oracle, MySQL, Sybase, and DB2) using Structured Query Language (SQL). JDBC stands for Java Database Connectivity. CU IDOL SELF LEARNING MATERIAL (SLM)

Java Data Base Connectivity 5 Java Java Application 1 Application 2 JDBC API Driver Manager JDBC Driver JDBC-ODBC Bridge ODBC Driver MySQL Oracle Microsoft Database Database Access Database Fig. 1.1: JDBC Architecture Table 1.1: How Does JDBC Work? How Does JDBC Work? JDBC API  Class.forName(“oracle.jdbc.driver.OracleDr The JDBC API is comprised of two Java packages: iver”) java.sql and javax.sql.  Calling Class.forName() automatically  java.sql: This is the initial package that creates an instance of the driver and provides the API for accessing and registers the driver with the processing data stored in a data source DriverManagerclass. The driver talks to a (usually a relational database) using the Java particular database such as Oracle or programming language. MySQL.  DriverManager is a connection factory  javax.sql: This is an extended package that class. In fact, it is the only class that can provides the API for server-side data source create database connections. The access and processing from the Java DriverManager uses drivers to create programming language. connections.  A Java database application uses the DriverManager class to get the java.sql.Connection object, which represents a database connection. 1.5 JDBC Driver A JDBC Driver allows a Java application/client to communicate with a SQL database. A JDBC driver is a Java class that implements the JDBC’s java.sql.Driver interface and understands how to convert program (and typically SQL) requests for a particular database. A Java program CU IDOL SELF LEARNING MATERIAL (SLM)

6 Advanced Internet Programming that uses the JDBC API loads the specified driver for a particular DBMS before it actually connects to a database. Types of Drivers Java Application JDBC API The Type 1 driver – JDBC-ODBC BRIDGE Bridge Driver translates its calls into ODBC calls .ODBC then interacts with the desired database. It is the most available but slowest type, and it works only on Microsoft Windows and Sun Solaris. There is only one driver in existence, sun.jdbc.odbc.JdbcOdbcDriver. Advantages DSN ODBC  Almost any database for which ODBC driver is installed, Driver can be accessed. DB  A type 1 driver is easy to install. Fig. 1.2: The JDBC- ODBC Bridge Driver Disadvantages  Performance overhead since the calls have to go through the JDBC overhead bridge to the ODBC driver, then to the native db connectivity interface.  The ODBC driver needs to be installed on the client machine.  Considering the client-side software needed, this might not be suitable for applets.  Will not be suitable for internet applications. Type 2 Driver - the Native-API Driver  It is written partly in the java programming language and partly native code that communicates with the client API of a database.  The kind of driver converts JDBC calls into calls on the client API for oracle, Sysbase, Enformics, IBM, DB-2or other DBMS.  When you use such a driver you must install some platform specific code in addition to java library. CU IDOL SELF LEARNING MATERIAL (SLM)

Java Data Base Connectivity 7 Advantages Java Application This type of diver is faster than JDBC-ODBC driver. Java API Driver Native API Driver Disadvantages  It requires local administration. Native API  Native libraries are required.  It is not a pure java driver. DB Fig. 1.3: The Native-API Driver Type 3 driver - the Network-Protocol Driver This driver converts the JDBC calls into a DBMS independent net protocol, which is then converted to the format as required by database by a middle server. Advantages Java Application This type of diver is faster than JDBC-ODBC driver. JDBC API Disadvantages Type 3 Driver  It requires local administration. Net common Protocol  Native libraries are required.  It is not a pure java driver. Middleware component DB Fig. 1.4: The Network-Protocol Driver Type IV: Native-Protocol -Java Driver This is the fastest way to communicate as the JDBC calls are directly converted to a network protocol used by DBMS. This driver is completely written in Java. CU IDOL SELF LEARNING MATERIAL (SLM)

8 Advanced Internet Programming Advantages Java Application  It is faster than all previous 3 drivers JDBC API  It is a pure java drivers.  No local administration is required Thin/Type 4 Driver Native Protocol OB Fig. 1.5: Native-Protocol-Java Driver 1.6 Java Database Connectivity Steps 1. Loading a Database Driver In this step of the jdbc connection process, Syntax we load the driver class by calling Class.forName() with the Driver class name as an try { argument. Once loaded, the Driver class creates Class.forName(\"sun.jdbc.odbc.JdbcOdbcDri an instance of itself. A client can connect to ver\"); //Or any other driver Database Server through JDBC Driver. Since } most of the Database servers support ODBC catch(Exception x){ driver therefore JDBC-ODBC Bridge driver is System.out.println( \"Unable to load the commonly used. The return type of the driver class!\" ); Class.forName (String ClassName) method is } “Class”. Class is a class in java.lang package. 2. Establishing Database Connection The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class manages the JDBC drivers that are installed on the system. Its getConnection() method is used to establish a connection to a database. It uses a username, password, and a jdbcurl to establish a connection to the database and returns a connection object. A jdbc Connection represents a session/connection with a specific database. Within the context of a Connection, SQL, PL/SQL statements are executed and results are returned. An application can have one or more CU IDOL SELF LEARNING MATERIAL (SLM)

Java Data Base Connectivity 9 connections with a single database. DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver. Syntax Connection con=DriverManager.getConnection(url,\"loginName\",\"Password\") 3. Creating a JDBC Statement object Once a connection is obtained we can interact with the database. Connection interface defines methods for interacting with the database via the established connection. To execute SQL statements, you need to instantiate a Statement object from your connection object by using the createStatement() method. A statement object is used to send and execute SQL statements to a database. Three kinds of Statements Statement: Execute simple sql queries without parameters. Statement createStatement() Creates an SQL Statement object. Prepared Statement: Execute precompiled sql queries with or without parameters. PreparedStatementprepareStatement(String sql) returns a new PreparedStatement object. PreparedStatement objects are precompiled SQL statements. Callable Statement: Execute a call to a database stored procedure. CallableStatementprepareCall(String sql) returns a new CallableStatement object. CallableStatement objects are SQL stored procedure call statements. 4. Executing the Statement object, and returning a jdbcresultSet. Statement interface defines methods that are used to interact with database via the execution of SQL statements. The Statement class has three methods for executing statements: executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to use is executeQuery. CU IDOL SELF LEARNING MATERIAL (SLM)

10 Advanced Internet Programming For statements that create or modify tables, the method to use is executeUpdate. execute() executes an SQL statement that is written as String object. ResultSet provides access to a table of data generated by executing a Statement. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The next() method is used to successively step through the rows of the tabular results. Syntax stmt=conn.createStatement(); inti=stmt.executeUpdate(\"insert into t1 values(101, ’ram’, ’3000’); 5. Closing Connection Closing the connection closes the object statement and ResultSet automatically. The close() method of Connection interface is used to close the connection. All the connections at the end of JDBC program every connection to the database and each database session has to be closed explicitly. One must not rely on the garbage collection especially when we do database programming as it is considered to be a poor programming practice. Any connection, which is associated with any connection object, must be closed using close() method. One must ensure that connection is closed and for that finally block must be inserted in the code. A finally block always executes, regardless if an exception occurs or not. To close above opened connection you should call close() method as follows: Syntax conn.close(); pstmt.close(); rs.close(); 1.7 JDBC Statements There are three types of statements: Statement: It is an interface which creates an object that is used to execute static SQL statements and obtain the result produced by it..Executes simple query without any parameter.createStatement() creates an SQL statement object. CU IDOL SELF LEARNING MATERIAL (SLM)

Java Data Base Connectivity 11 Syntax stmt=conn.createStatement(); inti=stmt.executeUpdate(\"insert into t1 values(101, ’ram’, ’3000’); Prepared Statement: It executes precompiled sql queries with or without parameters. A SQL statement is given to a PreparedStatement object, unlike a Statement object, when it is created. In most cases, this SQL statement is sent to the DBMS right away, where it is compiled. The PreparedStatement object contains not just a SQL statement, but a precompiled SQL statement. This means that when PreparedStatement is executed, the DBMS can just run PreparedStatement SQL statement without having to compile it first. PreparedStatement objects can be used for SQL statements with no parameters, but they must be used with SQL statements having parameters. One can use the same statement and supply it with different values every time it gets executed which is the main advantage of PreparedStatement. For example: prepareStatement (String sql) returns a new PreparedStatement object. PreparedStatement objects are precompiled SQL statements. Syntax PreparedStatementpstmt=null; pstmt=conn.prepareStatement(\"select * from t1\"); rs=pstmt.executeQuery(); while(rs.next()) { System.out.println(\"ID Is:\"+rs.getInt(\"id\")); System.out.println(\"Name Is:\"+rs.getString(\"name\")); System.out.println(\"Sal:\"+rs.getDouble(\"salary\")); } Callable Statement: a callable statement creates CallableStatement object just as a Connection object creates the Statement and PreparedStatement objects which is used to execute a call to a database stored procedure. CallableStatementprepareCall(String sql) returns a new CallableStatement object. CallableStatement objects are SQL stored procedure call statements. 1.8 Types of ResultSet The possible RSType are given below. If you do not specify any ResultSet type, you will automatically get one that is TYPE_FORWARD_ONLY. CU IDOL SELF LEARNING MATERIAL (SLM)

12 Advanced Internet Programming Type Description 1. ResultSet.TYPE_FORWARD_ONLY: The cursor can only move forward in the result set. 2. ResultSet.TYPE_SCROLL_INSENSITIVE: The cursor can scroll forward and backward, and the result set is not sensitive to changes made by others to the database that occur after the result set was created. 3. ResultSet.TYPE_SCROLL_SENSITIVE.: The cursor can scroll forward and backward, and the result set is sensitive to changes made by others to the database that occur after the result set was created. Concurrency of ResultSet The possible RSConcurrency are given below. If you do not specify any Concurrency type, you will automatically get one that is CONCUR_READ_ONLY. Concurrency Description 1. ResultSet.CONCUR_READ_ONLY- Creates a read-only result set. This is the default 2. ResultSet.CONCUR_UPDATABLE- Creates an updateable result set. 1.9 CRUD operation with Examples Example Based on Java Database Connectivity. Program 1: MySQL Database Connectivity using Command Prompt. import java.awt.*; s3=dis.readLine(); import java.awt.event.*; import java.sql.*; Class.forName(\"com.mysql.jdbc.Driver\") ; import java.io.*; // System.out.println(\"driver Registered class jdbcinsertdemo Successfully\"); { public static void main(String args[]) con=DriverManager.getConnection(\"jdbc:mysql { ://localhost:3306/cbs\",\"root\",\"cbs123\"); DataInputStream dis=new //System.out.println(\"Database Connected DataInputStream(System.in); Successfully\"); try PreparedStatement ps= con.prepareStatement(q); ps.setString(1,s1); ps.setString(2,s2); ps.setString(3,s3); CU IDOL SELF LEARNING MATERIAL (SLM)

Java Data Base Connectivity 13 { ps.executeUpdate(); Connection con; System.out.println(\"Successful...\"); String q=\"insert into } emp1(empid,empname,city)values(?,?,?)\"; String s1,s2,s3; catch(Exception e) System.out.println(\"Enter Employee Id:\"); { s1=dis.readLine(); System.out.println(\"Enter Employee System.out.println(\"Got an Exception\"); Name:\"); System.err.println(e.getMessage()); s2=dis.readLine(); } System.out.println(\"Enter City.....:\"); }} Execution of the Program. Database After Insertion 1.10 Practical Assignment 1. Develop JDBC application to create Login Form with MYSQL as backend. 2. Develop JDBC application for CRUD operations. 1.11 Summary Java Database Connectivity(JDBC) is an Application Programming Interface(API) used to connect Java application with Database. JDBC is used to interact with various type of Database such as Oracle, MS Access, My SQL and SQL Server. JDBC can also be defined as the platform- independent interface between a relational database and Java programming. It allows java program to execute SQL statement and retrieve result from database. CU IDOL SELF LEARNING MATERIAL (SLM)

14 Advanced Internet Programming 1.12 Key Words/Abbreviations  Database server: It is similar to data warehouse where the website store or maintain their data and information. A Database Server is a computer in a LAN that is dedicated to database storage and retrieval. The database server holds the Database Management System (DBMS) and the databases. Upon requests from the client machines, it searches the database for selected records and passes them back over the network.  JDBC: Java Database Connectivity  ODBC: Open Database Connectivity  DSN: data source name 1.13 Learning Activity 1. Explain CURD operations. ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- 2. Explain JDBC-ODBC bridge. ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- 1.14 Unit End Questions (MCQs and Descriptive) A. Descriptive Types Questions 1. What is JDBC? Explain the architecture of JDBC in detail. 2. Write and Explain steps of Java Database Connectivity. 3. Write short notes on JDBC Drivers? 4. What are Scrollable Resultset in JDBC? 5. Explain Rowsets and its types in JDBC? 6. Write short notes on JDBC transactions? 7. How to use Save Points in JDBC? 8. Write a program to show connectivity steps using MySql. 9. Write a program to retrieve data from oracle database using JDBC. CU IDOL SELF LEARNING MATERIAL (SLM)

Java Data Base Connectivity 15 8. Write a program to show connectivity steps using MySql. 9. Write a program to retrieve data from oracle database using JDBC. B. Multiple Choice/Objective Type Questions 1. Which of the following is true about JDBC architecture? (a) JDBC API layer provides the application-to-JDBC Manager connection. (b) JDBC Driver API layer supports the JDBC Manager-to-Driver Connection. (c) Both of the above. (d) None of the above. 2. Which of the following holds data retrieved from a database after you execute an SQL query using Statement objects? (a) ResultSet (b) JDBC driver (c) Connection (d) Statement 3. Which of the following type of JDBC driver is typically used for development and testing purposes only? (a) Type 1 (b) Type 2 (c) Type 3 (d). Type 4 4. Which of the following type of JDBC driver should be used when you are accessing one type of database, such as Oracle, Sybase, or IBM? (a) Type 1 (b) Type 2 (c) Type 3 (d) Type 4 5. Which of the following is a Metadata interfaces of JDBC? (a) DatabaseMetaData (b) ResultSetMetaData (c) Both of the above. (d) None of the above. Answers 1. (c), 2. (a), 3. (d), 4. (a), 5. (c) CU IDOL SELF LEARNING MATERIAL (SLM)

16 Advanced Internet Programming 1.15 References 1. https://www.studytonight.com/java/introduction-to-jdbc.php 2. https://www.javaworld.com/article/3388036/what-is-jdbc-introduction-to-java-database- connectivity.html 3. JDBC 4.2, Servlet 3.1, and JSP 2.3 Includes JSF 2.2 and Design Patterns, Black Book, 2ed CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 2 USER INTERFACE COMPONENTS Structure: 2.0 Learning Objectives 2.1 Introduction 2.2 MVC Architecture 2.3 Layout Manager 2.4 Introduction To JFC and SWING 2.5 Need of Swing Component 2.6 Difference between AWT and Swing 2.7 Hierarchy of Java Swing classes 2.8 Swing Features And Concepts 2.9 Swing API Components 2.10 Container class (Swing API Components - Top-Level Containers) 2.11 Jcomponent class 2.12 JButton 2.13 JLabel 2.14 JText 2.15 JTextArea 2.16 JcheckBox and JradioButton 2.17 Jlist CU IDOL SELF LEARNING MATERIAL (SLM)

18 Advanced Internet Programming 2.18 JcomboBox 2.19 JMenu and JPopupMenu Class 2.20 JMenu Item and JCheck Box Menu Item 2.21 J Radio Button Menu Item, 2.22 J scrollBar 2.23 Dialogs (Message, Confirmation, Input) 2.24 J File Chooser 2.25 Jcolor Chooser 2.26 Summary 2.27 Practical Assignment 2.28 Key Words/Abbreviations 2.29 Learning Activity 2.30 Unit End Questions (MCQs and Descriptive) 2.31 References 2.0 Learning Objectives After studying this unit, you will be able to:  Describe MVC architecture  Elaborate layout manager and Jcomponent class  Explain various user interface components 2.1 Introduction  MVC stands for Model View and Controller. It is a design pattern that separates the business logic, presentation logic and data. CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 19  Controller acts as an interface between View and Model. Controller intercepts all the incoming requests.  Model represents the state of the application i.e. data. It can also have business logic.  View represents the presentation i.e. UI(User Interface). Java Swing is a part of Java Foundation Classes (JFC) which was designed for enabling large-scale enterprise development of Java applications. Java Swing is a set of APIs that provides graphical user interface (GUI) for Java programs. Java Swing is also known as Java GUI widget toolkit. Java Swing or Swing was developed based on earlier APIs called Abstract Windows Toolkit (AWT). Swing provides richer and more sophisticated GUI components than AWT. The GUI components are ranging from a simple label to complex tree and table. Besides emulating look and feel of various platforms, Swing also provides the pluggable look and feel to allow look and feel of Java programs independent from the underlying platform. 2.2 MVC Architecture Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces on computers. It divides a given application into three interconnected parts. “Model” consist of database operations(CRUD operations; Create, Read, Update, Delete queries), “View” consist of Front end development (HTML, CSS, JavaScript etc) and “Controller” consist of the main business logic (Backend programming through server side languages such as PHP, JAVA etc). ‘Controller” controls the interaction/transactions between the “Model” and “Viewer”. MODEL VIEWER CONTROLLER Fig. 2.1: MVC Architecture Struts 2 MVC is realised by three core framework components: actions, results, and the ServletFilter. The diagram below shows how these three components interact with each other. CU IDOL SELF LEARNING MATERIAL (SLM)

20 Advanced Internet Programming request Invoke action Model Action Controller Interceptor Select result Servlet Filter View Web Browser Result Client Render result Fig. 2.2: MVC Struts 2 Servlet Filter The servlet filter acts as a controller in Struts 2. It inspects each incoming request to determine which Struts 2 action should handle the request. The framework handles all of the controller work for the application. All request URLs need to be mapped to actions with XML- based configuration files or Java annotations. Interceptors Interceptors execute before and after the request processing. They provide cross-cutting tasks so that they can be easily reused as well as separated from other architectural concerns. For example, validation parameters before invoking login action. Action Action handles the client requests in two different ways. First, the action plays an important role in the transfer of data from the request through to the view, whether it’s a JSP or other type of result. Second, the action must assist the framework in determining which result should render the view that will be returned in the response to the request. Result Result is a JSP or HTML page to create a view for client response. Struts 2 provide their own tags that we can use in JSP pages to create a response. Struts tags are great example of JSP Custom Tags. CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 21 2.3 Layout Manager Understanding LayoutManagers The Layout Managers are used to arrange components in a particular manner. Layout Manager is an interface that is implemented by all the classes of layout managers. There are following classes that represent the layout managers: java.awt.BorderLayout javax.swing.BoxLayout java.awt.FlowLayout javax.swing.GroupLayout java.awt.GridLayout javax.swing.ScrollPaneLayout java.awt.CardLayout javax.swing.SpringLayout etc. java.awt.GridBagLayout BorderLayout The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region (area) may contain one component only. It is the default layout of frame or window. The BorderLayout provides five constants for each region: 1. public static final int NORTH 4. public static final int WEST 2. public static final int SOUTH 5. public static final int CENTER 3. public static final int EAST Constructors used BorderLayout(): creates a border layout but with no gaps between the components. JBorderLayout(inthgap, intvgap): creates a border layout with the given horizontal and vertical gaps between the components. Example: Import java.awt.*; f.add(b1,BorderLayout.NORTH); Import javax.swing.*; f.add(b2,BorderLayout.SOUTH); public class BorderLayoutExample { f.add(b3,BorderLayout.EAST); JFrame f; f.add(b4,BorderLayout.WEST); BorderLayoutExample() { f.add(b5,BorderLayout.CENTER); f=new JFrame(); f.setSize(300,300); JButton b1=new JButton(\"NORTH\");; f.setVisible(true); } CU IDOL SELF LEARNING MATERIAL (SLM)

22 Advanced Internet Programming JButton b2=new JButton(\"SOUTH\");; public static void main(String[] args) { JButton b3=new JButton(\"EAST\");; newBorderLayoutExample(); JButton b4=new JButton(\"WEST\");; JButton b5=new JButton(\"CENTER\");; }} Output NORTH WEST CENTER EAST SOUTH GridLayout The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle. Constructors 1. GridLayout():creates a grid layout with one column per component in a row. 2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between the components. 3. GridLayout(int rows, int columns, inthgap, intvgap): creates a grid layout with the given rows and columns alongwith given horizontal and vertical gaps. Example: f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5) ; Import java.awt.*; Import javax.swing.*; f.add(b6);f.add(b7);f.add(b8);f.add(b9) public class MyGridLayoutExample { f.setLayout(new GridLayout(3,3)); JFrame f; f.setSize(300,300); MyGridLayoutExample() { f.setVisible(true); f=new JFrame(); } JButton b1=new JButton(\"A\"); public static void main(String[] args) { JButton b2=new JButton(\"B\"); new MyGridLayoutExample(); CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 23 JButton b3=new JButton(\"C\"); }} C JButton b4=new JButton(\"D\"); Output: F JButton b5=new JButton(\"E\"); JButton b6=new JButton(\"F\"); AB I JButton b7=new JButton(\"G\"); DE JButton b8=new JButton(\"H\"); GH JButton b9=new JButton(\"I\"); ; FlowLayout The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet or panel. Fields of FlowLayout class: public static final int LEFT public static final int LEADING public static final int RIGHT public static final int TRAILING public static final int CENTER Constructors  FlowLayout():creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap.  FlowLayout(int align):creates a flow layout with the given alignment and a default 5 unit horizontal and vertical gap.  FlowLayout(int align, inthgap, intvgap):creates a flow layout with the given alignment and the given horizontal and vertical gap Example: Import java.awt.*; f.setLayout(new Import javax.swing.*; FlowLayout(FlowLayout.RIGHT)); public class FlowLayoutDemo { f.setSize(300,300); JFrame f; f.setVisible(true); FlowLayoutDemo() { } f=new JFrame(); public static void main(String[] args) { JButton b1=new JButton(\"A\"); new FlowLayoutDemo(); CU IDOL SELF LEARNING MATERIAL (SLM)

24 Advanced Internet Programming JButton b2=new JButton(\"B\"); }} JButton b3=new JButton(\"C\"); JButton b4=new JButton(\"D\"); Output JButton b5=new JButton(\"5\"); f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b 5); BoxLayout The BoxLayout is used to arrange the components either vertically or horizontally. For this purpose, BoxLayout provides four constants. They are as follows: Class in BoxLayout public static final int LINE_AXIS public static final int PAGE_AXIS public static final int X_AXIS public static final int Y_AXIS Constructor BoxLayout(Container c, int axis):creates a box layout that arranges the components with the given axis. Example: Output: importjava.awt.*; importjavax.swing.*; public class BoxLayoutDemo extends Frame { Button buttons[]; public BoxLayoutDemo () { buttons = new Button [5]; for (inti = 0;i<5;i++) { buttons[i] = new Button (\"Button \" + (i + 1)); add (buttons[i]); } setLayout (new BoxLayout (this, BoxLayout.Y_AXIS)); setSize(400,400); setVisible(true); } public static void main(String args[]) { BoxLayoutDemo b=new BoxLayoutDemo(); }} CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 25 CardLayout The CardLayout class manages the components in such a manner that only one component is visible at a time. It treats each component as a card that is why it is known as CardLayout. Constructors  CardLayout():creates a card layout with zero horizontal and vertical gap.  CardLayout(inthgap, intvgap):creates a card layout with the given horizontal and vertical gap. Methods of CardLayout  public void next(Container parent):is used to flip to the next card of the given container.  public void previous(Container parent):is used to flip to the previous card of the given container.  public void first(Container parent): is used to flip to the first card of the given container.  public void last(Container parent): is used to flip to the last card of the given container.  public void show(Container parent, String name): is used to flip to the specified card with the given name. Example: b3=new JButton(\"Animal\"); b1.addActionListener(this); Import java.awt.*; b2.addActionListener(this); Import java.awt.event.*; b3.addActionListener(this); Import javax.swing.*; c.add(\"a\",b1);c.add(\"b\",b2);c.add(\"c\",b3); } public class CardLayoutDemo extends JFrame public void actionPerformed(ActionEvent e) { implements ActionListener { card.next(c); } CardLayout card; public static void main(String[] args) { JButton b1,b2,b3; CardLayoutDemo cl=new CardLayoutDemo(); Container c; cl.setSize(400,400); CardLayoutDemo() { cl.setVisible(true); c=getContentPane(); cl.setDefaultCloseOperation(EXIT_ON_CLOSE card=new CardLayout(40,30); ); } } c.setLayout(card); b1=new JButton(\"Book\"); b2=new JButton(\"Flower\"); CU IDOL SELF LEARNING MATERIAL (SLM)

26 Advanced Internet Programming Output: Flower 2.4 Introduction to JFC and Swing JFC is short for Java Foundation Classes, which encompass a group of features for building graphical user interfaces(GUIs) and adding rich graphics functionality and interactivity to Java applications. Swing is a set of program components for Java programmers that provide the ability to create graphical user interface ( GUI ) components, such as buttons and scroll bars that are independent of the windowing system for specific operating system . Swing components are used with the Java Foundation Classes ( JFC ). 2.5 Need of Swing Component Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT). Unlike AWT components, Swing components are not implemented by platform-specific code. Instead, they are written entirely in Java and therefore are platform-independent. It is defined as containing the features shown in the table below. CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 27 2.6 Difference between AWT and Swing Feature Table 2.1: Difference between AWT and Swing Description AWT components are platform-dependent. Java swing components are platform- independent. AWT components are heavyweight. Swing components are lightweight. AWT doesn’t support pluggable look and feel. Swingsupports pluggable look and feel. AWT provides less components than Swing. Swing provides more powerful components such as tables, lists, scroll panes, color chooser, tabbed pane etc. AWTdoesn’t follows MVC (Model View Swingfollows MVC. Controller) where model represents data, view represents presentation and controller acts as an interface between model and view. 2.7 Hierarchy of Java Swing Classes Object Component JLabel JList Container JComponent JTable JComboBox Window Panel JSlider JMenu Frame Applet AbstractButton Dialog JButton Fig. 2.3: Hierarchy of Java Swing Classes CU IDOL SELF LEARNING MATERIAL (SLM)

28 Advanced Internet Programming 2.8 Swing Features and Concepts Swing Components and the Containment Hierarchy- Swing provides many standard GUI components such as buttons, lists, menus, and text areas, which you combine to create your program’s GUI. It also includes containers such as windows and toolbars. Layout Management: Layout management is the process of determining the size and position of components. By default, each container has a layout manager—an object that performs layout management for the components within the container. Components can provide size and alignment hints to layout managers, but layout managers have the final say on the size and position of those components. Event Handling: Event handling is how programs respond to external events, such as the user pressing a mouse button. Swing programs perform all their painting and event handling in the event-dispatching thread. Every time the user types a character or pushes a mouse button, an event occurs. Any object can be notified of the event. All it has to do is implement the appropriate interface and be registered as an event listener on the appropriate event source. Swing components can generate many kinds of events. Here are a few examples: Table 2.2: Event Handling Examples Act that results in the event Listener type User clicks a button, presses Return while typing in a text field, or chooses Action Listener a menu item User closes a frame(main window) Window Listener User presses a mouse button while the cursor is over a component Mouse Listener User moves the mouse over a component Mouse Motion Listener Component becomes visible Component Listener Component gets the keyboard focus Focus Listener Table or list selection changes List Selection Listener Painting: Painting means drawing the component on-screen. Although it’s easy to customize a component’s painting, most programs don't do anything more complicated than customizing a component’s border. Threads and Swing: If you do something to a visible component that might depend on or affect its state, then you need to do it from the event-dispatching thread. This isn’t an issue for many simple programs, which generally refer to components only in event-handling code. CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 29 More Swing Features and Concepts: Swing offers many features, many of which rely on support provided by the JComponent class. Some of the interesting features include support for icons, actions, Pluggable Look & Feel technology, assistive technologies, and separate models. 2.9 Swing API Components 2.9.1 JFrames A frame, Implemented as an instance of the JFrame class, is a window that has decorations such as a border, a title, and buttons for closing and iconifying the window. Applications with a GUI typically use at least one frame. By default, when the user closes a frame on screen, the frame is hidden .Although invisible, the frame still exists and the program can make it visible again. If you want different behavior, then you need to either register a window listener that handles window-closing events, or you need to specify default close behavior using the setDefaultCloseOperation method. You can even do both. The argument to setDefaultCloseOperation must be one of the following values, which are defined in the Window Constants interface:  DO_NOTHING_ON_CLOSE:- Don’t do anything when the user’s requests that the frame close. Instead, the program should probably use a window listener that performs some other action in its window closing method.  HIDE_ON_CLOSE (the default): Hide the frame when the user closes it. This removes the frame from the screen.  DISPOSE_ON_CLOSE:Hide and dispose of the frame when the user closes it. This removes the frame from the screen and frees up any resources used by it. Constructors Create a frame that is initially invisible. Call set Visible(true)on the frame to make it visible. The String argument provides a title for the frame. You JFrame() can also use set Title to set a frame’s title. JFrame(String) Methods 1. ContainergetContentPane()-Returns the content Pane object for this frame. 2. JMenuBargetJMenuBar() –Returns the menu bar set on this frame. 3. voidsetDefaultCloseOperation(int operation) -Sets the operation that will happen by default when the user initiates a \"close\" on this frame. CU IDOL SELF LEARNING MATERIAL (SLM)

30 Advanced Internet Programming 4. voidsetJMenuBar(JMenuBarmenubar)-Sets the menubar for this frame. 5. void setVisible(Boolean b) - Shows or hides this component depending on the value of parameter b. 6. voidsetLocation(intx,inty)-Moves this component to a new location. The top-left corner of the new location is specified by the x and y parameters in the coordinate space of this component's parent. 7. voidpack()-Causes this Window to be sized to fit the preferred size and layouts of its sub components. If the window and/or its owner are not yet displayable, both are made displayable before calculating the preferred size. The Window will be validated after the preferred Size is calculated. 8. voidsetTitle(Stringtitle)-Sets the title for this frame to the specified string. 2.9.2 JApplet JApplet is an extended version of java.applet. Applet that adds support for the JFC/Swing component architecture. The JAppletclass is slightly incompatible with java.applet.Applet. JApplet contains a JRootPane as it’s only child. The content Pane should be the parent of any children of the JApplet. To add the child to the JApplet’s content Pane we use the getContentPane()method and add the components to the content Pane. The same is true for setting LayoutManagers, removing components, listing children, etc. All these methods should normally be sent to the contentPane()insteadoftheJAppletitself.ThecontentPane()willalwaysbe non-null. Attempting to set it to null will cause the JApplet to throw an exception. The default contentPane() will have a Border Layout manager set on it. JApplet adds two major features to the functionality that it inherits from java.applet.Applet. First, Swing applets provide support for assistive technologies. Second, because JApplet is a top- level Swing container, each Swing applet has a root pane. The most noticeable results of the root pane’s presence are support for adding a menu bar and the need to use a contentpane. Constructor JApplet()- Creates a swing applet instance CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 31 Methods 1. Container getContentPane()-Returns the contentPane object for this applet. 2. void setJMenuBar (JMenuBarmenuBar)- Sets the menubar for this applet. 3. void setLayout (LayoutManagermanager) - By default the layout of this component may not be set, the layout of its contentPane should be set instead. 4. void update(Graphics g)-Just calls paint(g). java.applet.Applet class For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet. 1. Public void init(): is used to initialized the Applet. It is invoked only once. 2. public void start():is invoked after the init() method or browser is maximized. It is used to start the Applet. 3. public void stop():is used to stop the Applet. It is invoked when Applet is stop or browser is minimized. 4. public void destroy():is used to destroy the Applet. It is invoked only once. java.awt.Component class The Component class provides 1 life cycle method of applet. 1. public void paint(Graphics g):is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle, arc etc. How to run an Applet? There are two ways to run an applet 1. By html file. 2. By appletViewertool . Simple example of Applet by appletviewer tool: To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is for testing purpose only. CU IDOL SELF LEARNING MATERIAL (SLM)

32 Advanced Internet Programming //First.java /* Import java.applet.Applet; <applet code=\"First.class\" width=\"300\" Import java.awt.Graphics; height=\"300\"> Public class First extends Applet { </applet> Public void paint(Graphicsg) { */ g.drawString(\"welcome to applet\",150,150); To execute the applet by appletviewer tool, } write in command prompt: } c:\\>javac First.java c:\\>appletviewer First.html 2.9.3 J Window A JWindow is a container that can be displayed anywhere on the user’s desktop. It does not have the title bar, window- management buttons, or other trimmings associated with a JFrame, but it is still a \"first-class citizen\" of the user’s desktop, and can exist anywhere on it. The JWindow component contains a JRootPane as its only child. The content Pane should be the parent of any children of the JWindow. From the older java.awt.Window object you would normally do something like this: window.add(child); However, using JWindow you would code: window.getContentPane().add(child); The same is true of setting Layout Managers, removing components, listing children, etc. All these methods should normally be sent to the content Pane instead of the JWindow itself. The content Pane will always be non-null. Attempting to set it to null will cause the JWindow to throw an exception. The default content Pane will have a Border Layout manager set on it. Constructor 1. JWindow()-Creates a window with no specified owner. 2. JWindow (Frameowner)-Creates a window with the specified owner frame. Methods 1. ConatinergetContentPane()-Returns the content Pane object for this applet. 2. voidsetLayout(LayoutManagermanager)- By default the layout of this component may not be set, the layout fits content Pane should be set instead. 3. voidupdate(Graphicsg)-Just calls paint(g). 4. void windowInit() - Called by the constructors to init the JWindow properly. CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 33 2.10 Container Class (Swing API Components - Top-Level Containers) Swing provides three generally useful top-level container classes: JFrame JDialog, and JApplet. To appear on screen, every GUI component must be part of a containment hierarchy. Each containment hierarchy has a top-level container as its root. Each top-level container has a content pane that, generally speaking, contains the visible components in that top-level container's GUI. You can optionally add a menu bar to a top-level container. The menu bar is positioned within the top-level container, but outside the content pane. 2.10.1 Top-Level Containers and Containment Hierarchies Each program that uses Swing components has at least one top-level container. This top-level container is the root of a containment hierarchy—the hierarchy that contains all of the Swing components that appear inside the top-level container. As a rule, a standalone application with a Swing-based GUI has at least one containment hierarchy with a JFrame as its root. 2.10.2 Adding Components to the ContentPane Here’s the code that is used to get a frame’s content pane and add the yellow label to it: frame.getContentPane().add(yellow Label, Border Layout.CENTER); As the code shows, you find the contentpane of a top-level container by calling the getContentPane method. The default content pane is a simple intermediate container that inherits from JComponent, and that uses a BorderLayout as its layout manager. It’s easy to customize the content pane -- setting the layout manager or adding a border, for example. The getContentPane method returns a Container object, not a JComponentobject. 2.10.3 Adding a MenuBar All top-level containers can, in theory, have a menubar. In practice, however, menubars usually appear only in frames and perhaps in applets. To add a menubar to a frame or applet, you create a JMenuBarobject, populate it with menus, and then call setJMenuBar .To adds a menu bar to its frame use this code: frame.setJMenuBar(MenuBar_Name); 2.11 Jcomponent class The JComponent Class With the exception of top-level containers, all Swing components whose names begin with “J” descend from the JComponentclass. For example, JPanel, JScrollPane, JButton, and JTable all CU IDOL SELF LEARNING MATERIAL (SLM)

34 Advanced Internet Programming inherit from JComponent. However, JFrame and JDialog don’t because they implement top-level containers. The JComponent class extends the Container class, which itself extends Component. The Component class includes everything from providing layout hints to supporting painting and events. The Container class has support for adding components to the container and laying them out. This section’s API tables summarize the most often used methods of Component and Container, as well as of JComponent. Constructor JComponent() :- Default JComponent constructor. Methods Method Description Modifier and Type setActionMap(ActionMap am) It sets the ActionMap to am. void void setBackground(Color bg) It sets the background color of this component. void void setFont(Font font) It sets the font for this component. void setMaximumSize(Dimension It sets the maximum size of this component to maximumSize) a constant value. protected void setMinimumSize(Dimension It sets the minimum size of this component to void minimumSize) a constant value. void String setUI(ComponentUI newUI) It sets the look and feel delegate for this component. Container setVisible(boolean aFlag) It makes the component visible or invisible. TransferHandler setForeground(Color fg) It sets the foreground color of this component. getToolTipText(MouseEvent It returns the string to be used as the tooltip for event) event. getTopLevelAncestor() It returns the top-level ancestor of this getTransferHandler() component (either the containing Window or Applet), or null if this component has not been added to any container. It gets the transferHandler property. CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 35 Java JComponent Example JFrame frame=newJFrame(\"JComponentExample\"); Import java.awt.Color; frame.setSize(300,200); Import java.awt.Graphics; frame.setDefaultCloseOperation(JFrame.EXIT Import javax.swing.JComponent; _ON_CLOSE); Import javax.swing.JFrame; //addtheJComponenttomainframe Class MyJComponent extends JComponent{ frame.add(com); Public void paint (Graphicsg) { frame.setVisible(true); g.setColor(Color.green); } g.fillRect(30,30,100,100); } }} public class JComponentExample { Output public static void main(String[]arguments) { MyJComponent com=new MyJComponent(); //createabasicJFrame JFrame.setDefaultLookAndFeelDecorated(true); 2.12 JButton A JButton class provides the functionality of a pushbutton. JButton allows an icon, a string or both to be associated with the push button. JButton is a sub class of Abstract Button which extends JComponent. Constructor Purpose JButton(Action) Create a JButton instance, initializing it to have the specified JButton(String, Icon) JButton(String) text/image/action. JButton(Icon) JButton() Methods Set or get the button’s properties according to values from the Action instance. void setAction(Action) ActiongetAction() Set or get the text displayed by the button. void setText(String) StringgetText() voidsetIcon(Icon) IcongetIcon() Set or get the image displayed by the button when the button isn’t selected or pressed. CU IDOL SELF LEARNING MATERIAL (SLM)

36 Advanced Internet Programming void setDisabledIcon(Icon) Set or get the image displayed by the button when it IcongetDisabledIcon() is disabled. If you do not specify a disabled image, then the look and feel creates one by manipulating void setPressedIcon(Icon) the default image. IcongetPressedIcon() Set or get the image displayed by the button when it void setAction(Action) ActiongetAction() is being pressed. Set or get the button’s properties according to values Button Example from the Action instance. import java.awt.*; f.setSize(400,400); import java.swing.*; f.setLayout(null); public class Button1 f.setVisible(true); { }} public static void main(String[] args) { Output: JFrame f=new JFrame(\"Button Example\"); JButton b=new JButton(\"Click Here\"); b.setBounds(50,100,80,30); f.add(b); 2.13 Jlabel With the JLabel class, you can display unselectable text and images. If you need to create a component that displays a string, an image, or both, you can do so by using or extending JLabel. If the component is interactive and has a certain state, use a button instead of a label. By specifying HTML code in a label’s text, you can give the label various characteristics such as multiple lines, multiple fonts or multiple colors. If the label uses just a single color or font, you can avoid the overhead of HTML processing by using the set Foreground or set Font method instead. See Using HTML in Swing Components for details. Note that labels are not opaque by default. If you need to paint the label’s background, it is recommended that you turn its opacity property to “true”. The following code snippet shows how to do this. label.setOpaque(true); CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 37 Method or Constructor Purpose JLabel(Icon) Creates aJLabelinstance, initializing it to have the specified JLabel(Icon, int) JLabel(String) text/image/alignment. Theintargument specifies the horizontal JLabel(String, Icon, int) JLabel(String, int) alignment of the label’s contents within its drawing area. The JLabel() horizontal alignment must be one of the following constants defined in void setText(String) String getText() theSwing Constants interface void setIcon(Icon) Icon getIcon() (whichJLabelimplements):LEFT,CENTER,RIGHT,LEADING, void setDisabledIcon(Icon) orTRAILING. For ease of localization, we strongly recommend Icon getDisabledIcon() usingLEADINGandTRAILING, rather thanLEFTandRIGHT. Sets or gets the text displayed by the label. You can use HTML tags to format the text, as described inUsing HTML in Swing Components. Sets or gets the image displayed by the label. Sets or gets the image displayed by the label when it is disabled. If you do not specify a disabled image, then the look and feel creates one by manipulating the default image. Example: import java.awt.GridLayout; // We can position of the text, relative to the icon: import java.awt.event.WindowAdapter; jlbLabel1.setVerticalTextPosition(JLabel.BOTTOM); import java.awt.event.WindowEvent; jlbLabel1.setHorizontalTextPosition(JLabel.CENTE import javax.swing.JLabel; R); import javax.swing.JPanel; jlbLabel2 = new JLabel(\"Text Only Label\"); import javax.swing.JFrame; jlbLabel3 = new JLabel(icon); // Label of Icon Only import javax.swing.ImageIcon; // Add labels to the Panel public class JlabelDemo extends JPanel { add(jlbLabel1); JLabel jlbLabel1, jlbLabel2, jlbLabel3; add(jlbLabel2); public JlabelDemo() { add(jlbLabel3); ImageIcon icon = new ImageIcon(\"java- } swing-tutorial.JPG\", \"My Website\"); public static void main(String[] args) { // Creating an Icon JFrame frame = new JFrame(\"jLabel Usage setLayout(new GridLayout(3, 1)); Demo\"); // 3 rows, 1 column Panel having Grid frame.setContentPane(new JlabelDemo()); Layout frame.pack(); jlbLabel1 = new JLabel(\"Image with Text\", frame.setVisible(true); icon, JLabel.CENTER); } } CU IDOL SELF LEARNING MATERIAL (SLM)

38 Advanced Internet Programming 2.14 JText A text field is a basic text control that enables the user to type a small amount of text. When the user indicates that text entry is complete (usually by pressing Enter), the text field fires an action event. If you need to obtain more than one line of input from the user, use a text area. Method or Constructor Purpose JTextField() Creates a text field. When present, theintargument specifies the JTextField(String) desired width in columns. TheStringargument contains the field's JTextField(String, int) initial text. JTextField(int) void setText(String) String getText() Sets or obtains the text displayed by the text field. (defined inJTextComponent) The object of a TextField class is a text component that allows the editing of a single line text. It inherits TextComponent class. Swing TextField Class Declaration public class TextField extends TextComponent Example: import java.awt.*; f.add(t1); f.add(t2); import java.swing.*; f.setSize(400,400); class TextFielddemo f.setLayout(null); { f.setVisible(true); public static void main(String args[]) } { } JFrame f= new JFrame(\"TextField Demo\"); JTextField t1,t2; Output: t1=new JTextField(\"Welcome to cbs college.\"); t1.setBounds(50,100, 200,30); t2=new JTextField(\"core java \"); t2.setBounds(50,150, 200,30); CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 39 2.15 JtextArea The JTextArea class provides a component that displays multiple lines of text and optionally allows the user to edit the text. If you need to obtain only one line of input from the user, you should use atext field. If you want the text area to display its text using multiple fonts or other styles, you should use an editor pane or text pane. If the displayed text has a limited length and is never edited by the user, use a label. Many of the Tutorial’s examples use uneditable text areas to display program output. Here is a picture of an example called TextDemo that enables you to type text using a text field (at the top) and then appends the typed text to a text area (underneath). Method or Constructor Purpose JTextArea() Creates a text area. When present, JTextArea(String) theStringargument contains the initial text. JTextArea(String, int, int) Theintarguments specify the desired width in JTextArea(int, int) columns and height in rows, respectively. void setText(String) Sets or obtains the text displayed by the text area. String getText() (defined inJTextComponent) Example import java.awt.Dimension; JTextArea text import java.awt.FlowLayout; Areal=newJTextArea(text,5,10); import javax.swing.JFrame; import javax.swing.JScrollPane; textAreal.setPreferredSize(newDimensio import javax.swing.JTextArea; n(100,100)); public class JTextAreaTest { public static void main(String[]args) { JTextArea JFrame frame=newJFrame(\"JTextAreaTest\"); textArea2=newJTextArea(text,5,10); frame.setLayout(newFlowLayout()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_C textArea2.setPreferredSize(newDimensi LOSE); on(100,100)); String text=\"AJTextAreaobjectrepresentsamultilineareafordis JScrollPane scroll playingtext.\" Pane=newJScrollPane(textArea2,JScroll Pane.VERTICAL_SCROLLBAR_ALWA YS, JScrollPane.HORIZONTAL_SCROLLBA R_ALWAYS); textAreal.setLineWrap(true); textArea2.setLineWrap(true); CU IDOL SELF LEARNING MATERIAL (SLM)

40 Advanced Internet Programming +\"Youcanchangethenumberoflinesthatcanbedisplayed frame.add(textAreal); atatime,\" frame.add(scrollPane); +\"aswellasthenumberofcolumns.Youcanwraplinesand frame.pack(); wordstoo.\" frame.setVisible(true); +\"YoucanalsoputyourJTextAreainaJScrollPanetomakei }} tscrollable.\"; 2.16 JCheckBox and JradioButton A JCheckBox class provides the functionality of a Check box. Its immediate superclass is JToggleButton which provides supportfor2statebuttons. Constructor Purpose JCheckBox(String) Create a JCheckBox instance. The string argument specifies the text, if any, that the check box should JCheckBox(String,boolean) display. Similarly, the Icon argument specifies the image that should be used instead of the look and JCheckBox(Icon) feel’s default checkbox image. Specifying the Boolean argument as true initializes the check box to JCheckBox(Icon,boolean) be selected. If the Boolean argument is absent or JCheckBox(String,Icon) JCheckBox(String,Icon, false, then the checkbox is initially unselected boolean) JCheckBox() Methods Returns the action command for this button. Returns the button’s text. StringgetActionCommand() Returns the state of the button. StringgetText() Enables (or disables) the button. booleanisSelected() Sets the state of the button. voidsetEnabled(booleanb) Sets the button’s text. voidsetSelected(booleanb) voidsetText(Stringtext) Example of checkBox: import javax.swing.*; JCheckBox c4 =new JCheckBox(\"DBMS\"); import java.io.*; p.add(c1); import java.awt.*; p.add(c2); class checkboxdemo p.add(c3); { p.add(c4); CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 41 public static void main(String arg[]) f.add(p); { f.setSize(200,200); JFrame f=new JFrame(\"frame window\"); f.setVisible(true); JPanel p=new JPanel(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CL OSE); JLabel l=new JLabel(\"programming languages\"); }} p.add(l); Output: JCheckBox c1 =new JCheckBox(\"SQL\"); JCheckBox c2 =new JCheckBox(\"ASP.NET\"); JCheckBox c3 =new JCheckBox(\"LINUX\"); This class represents swing RadioButtons. RadioButtons are a list of options out of which anyone is selected at a time. The RadioButton must be configured into a group such that only one of the buttons can be selected at a time. For this we use the Button Group class. Constructors JRadioButton(Icon i) JRadioButton(String s, boolean state) JRadioButton(Icon i, boolean state) JRadioButton( String s,Iconi) JRadioButton(String s) JRadioButton( String s,Iconi, boolean state) Example of RadioButton JRadioButton r4=new JRadioButton(\" BMM\"); bg.add(r1); import javax.swing.*; bg.add(r2); import java.io.*; bg.add(r3); import java.awt.*; bg.add(r4); class radiobutton p.add(r1); { p.add(r2); public static void main(String arg[]) p.add(r3); { p.add(r4); JFrame f=new JFrame(\" frame window\"); f.add(p); JPanel p=new JPanel(); f.setSize(300,300); JLabel l=new JLabel(\"Courses:\"); f.setVisible(true); JRadioButton r1=new JRadioButton(\" f.setDefaultCloseOperation(JFrame.EXIT_ON_CLO BSc(IT)\"); SE); JRadioButton r2=new JRadioButton(\" BMS\"); CU IDOL SELF LEARNING MATERIAL (SLM)