Professional Documents
Culture Documents
Abstract Window Toolkit (AWT) is a set of application program interfaces (API s) used by Java programmers to create graphical user interface ( GUI ) objects, such as text fields, buttons, toggle buttons, scroll bars, windows, and menus. AWT contains several graphical widgets which can be added and positioned to the display area with a layout manager. AWT API was introduced in JDK 1.0. It contains all classes to write the program that interface between the user and different windowing toolkits. The AWT is now part of the Java Foundation Classes (JFC) the standard API for providing a graphical user interface (GUI) for a Java program. It is a portable GUI library for stand-alone applications and/or applets. A rich set of user interface components. A robust event-handling model. Graphics and imaging tools, including shape, color, and font classes. Layout managers, for flexible window layouts that don't depend on a particular window size or screen resolution. Create windows and menus for standalone Java applications.
Components of AWT:
1. Container. Containers (such as Frame, Panel and Applet) are used to hold components (such as Button, Label, and TextField.) in a specific layout . Canvases. 2. Canvases. It is a simple drawing surface. Canvases are good for painting images or other graphics operation. . 3. UI component: These can include buttons, lists, simple popup menus, checkboxes, test fields and other typical elements of a user interface. 4. Window construction components: These include windows, frames, menubars, and dialogs. These are listed separately from the other User Interface components (UI components) .
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 2
Button: Button are simple UI components that trigger some action in your interface when
they are pressed. Class Button has following constructors : Button(): create an empty button with no label. Button(String): create a button with the given string object as a label.
CheckBox: CheckBox: This component is used to create check boxes in your application. Checkboxes
have two states on and off. (or checked and unchecked or selected and unselected or true and false). Checkbox(): create an empty checkbox, unselected. Checkbox(String): create a checkbox with the given string as a label. Checkbox(String, null, Boolean): create a checkbox with the given string and given Boolean value(true/false).
Button: Radio Button: This is the special case of the Checkbox component. This is used as a
group of checkboxes which group name is same. Only one Checkbox from a Checkbox group can be selected at a time. Create an instance of CheckboxGroup class.
Choice Choice Menus: Choice menus are popup (or pulldown) menus that enable you to select
an item from that menu. The menu then displays that choice in the screen. To create a choice menu, create an instance of the Choice class, and then use the addItem() method to add individual items to it in the order in which they should appear: Create an instance of Choice class.
PasswordFields: PasswordFields: Password Fields allow you to enter any values and that does not echo
characters you entered. PasswordField(int): PasswordField(int): Create an empty text field with the given width characters.
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 4
Layout Managers:
A layout manager is an object that controls the size and position (layout) of
components inside a Container object. For example, a window is a container that contains components such as buttons and labels.
FlowLayout - FlowLayout is the default layout manager for all Panels. It simply lays out
components from left to right in a row. If the row is full, it arranges in the next row from left to right. FlowLayout: Default FlowLayout, which centers components and leaves five pixels of space between each component. FlowLayout(int how): Create a FlowLayout with the given alignment value. FlowLayout.LEFT FlowLayout.CENTER FlowLayout.RIGHT
BorderLayout BorderLayout - BorderLayout is the default layout manager for all Windows, such as
Frames and Dialogs. It uses five areas to hold components: north, south, east, west, and center. All extra space is placed in the center area. BorderLayout() : Create a default border layout. BorderLayout( int horz, int vert): Create a border layout to specify the horizontal and vertical space left between components in horz and vert, respectively. Specify the Regions: BorderLay BorderLayout.CENTER BorderLay BorderLayout.EAST BorderLayout.WEST BorderLay BorderLay BorderLayout.NORTH BorderLay BorderLayout.SOUTH
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 5
GridLayout - The container is divided up into identically sized spaces. The components are
placed from top left to right going down. Unlike FlowLayout, every component gets any equal area even if they are different sizes. GridLayout() : Creates a grid layout with a default of one column per component, in a single row. GridLayout(int rows, int cols) : Creates a grid layout with the specified number of rows and columns. GridLayout(int rows, int cols, int hgap, int vgap) : Creates a grid layout with the specified number of rows and columns.
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 6
is at the core of successful GUI programming. Most events to which a GUI application will respond
The Delegation Event Model: The modern approach to handling events is based on the
delegation event model. A source generates an event and sends it to one or more listeners. The listener simply waits until it receives an event. Once received, the listener processes the event and then returns. The advantage of this design is that the application logic that processes events is cleanly separated from the user interface logic that generates those events
Event: An event is an object that describes a state change in a source. Event Source: A source is an object that generates an event. Event Listeners: A listener is an object that is notified when an event occurs. It has two
major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 7
Java provides a special feature called an adapter class that can simplify
the creation of event handlers in certain situations. An adapter class provides an empty implementation of all method in an event Listener interface. Adapter class is useful when you want to receive at process only some of event that is handled by a particular event Listener interface. For example Mouse motion adapter class has two method mouse drag & mouse move. This signature of these empty methods exactly defines the mouse motion Listener interface.
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 8
class ActionHandler implements ActionListener { public void actionPerformed(ActionEvent ae) { //Perform Task Here } }
Similarly we can implement any type of Event listener like ActionListener, MouseListener, KeyListener, WindowListener etc, or we can extend Adapter Classes like MouseAdapter, KeyAdapter, WindowAdapter etc. 3) Registering implemented Listener to event source.
Button b1 = new Button("ADD"); Button b2 = new Button("SUB"); //instantiating Event Handler ActionHandler ah = new ActionHandler(); //Registering instantiated handler to event sources. b1.addActionListener(ah); b2.addActionListener(ah);
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 9
import java.awt.*; import java.awt.event.*; public class Calculator extends Frame implements ActionListener TextField t1, t2, t3; Label l1, l2, l3; Button b1, b2; public Calculator() { setSize(250,200); setVisible(true); setTitle("CALC"); setBackground(Color.GRAY); //Setting Flowlayout on Calculator Frame setLayout(new FlowLayout(FlowLayout.CENTER)); //For Window Close Operation addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) System.exit(0); }}); t1 = new TextField(20); t2 = new TextField(20); t3 = new TextField(20); b1 = new Button("ADD"); b2 = new Button("SUB"); b1.addActionListener(this); b2.addActionListener(this); l1 = new Label("Number One"); l2 = new Label("Number Two"); l3 = new Label("OPR RESULT"); {
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 10
add(l2); add(b1);
add(t2); add(b2);
public void actionPerformed(ActionEvent ae) { if(ae.getSource() == b1) { int n1 = Integer.parseInt(t1.getText()); int n2 = Integer.parseInt(t2.getText()); int sum = n1 + n2; t3.setText(String.valueOf(sum)); } if(ae.getSource() == b2) { int n1 = Integer.parseInt(t1.getText()); int n2 = Integer.parseInt(t2.getText()); int sum = n1 - n2; t3.setText(String.valueOf(sum)); } } //End Of Handler Method }//End Of Calculator Class class GUIDemo { public static void main(String [] ar) { Calculator c = new Calculator(); }//End Of Main Method }//End Of GUI Demo
Output : C:\United\ GUIDemo.java C:\United\CS>javac GUIDemo.java C:\United\ C:\United\CS>java GUIDemo
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 11
the release of JDK 1.1. Swing is a rich set of easy-to-use, easy-to-understand JavaBean GUI components that can be dragged and dropped as "GUI builders" in visual programming environment. Swing is now an integral part of Java since JDK 1.2. An effort to incorporate many of the features in Netscape's IFC as well as some aspects of IBM stuff First released in March of 1998 with nearly 250 classes and 80 interfaces. Advanced graphical programming. Provides assistive technology for the disabled. High quality 2D graphics and images. Pluggable look and feel supports. Drag-and-drop support between Java and native applications. Swing is not a replacement for the AWT. - Needed to support truly architecture independent interfaces - Contains more powerful components Why bother? - Increased acceptance (many more supported architectures) - AWT based on architecture-specific widgets.
Pluggable Look and Feel: The Look and Feel that means the dramatically changing in the Feel: component like JFrame, JWindow, JDialog etc. for viewing it into the several type of window.
LnFs are increasingly important Similar look of underlying environment LnFs for UNIX, Windows, Apple. (Default is called Metal) LnFs can be changed at run-time
Lightweight - components which are not dependent on native source to render Heavyweights are unwieldy because: - Equivalent components may act differently on different platforms - LnF is tied to the host environment
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 12
Tables Trees Sliders Progress Bars Internal Frames Text Components (Very nice) Tool tips Support for undo/redo Support for Multiple Document Interfaces (MDI) with InternalFrames.
Swings Component :
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 13
Feature
Swing supports a wider range of feature like icons and pop-up tooltips for components.
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 14
language. Because it has no space for complexities. At the initial stages of its development it was called as OAK. OAK was designed for handling set up boxes and devices. But later new features were added to it and it was renamed as Java. Java became a general purpose language that had many features to support it as the internet language. Few of the features that favors it to be an internet language are: Cross Platform Compatibility: The java source files (java files with .java extension) after compilation generate the bytecode (the files with .class extension) which is further converted into the machine code by the interpreter. The byte code once generated can execute on any machine having a JVM. Every operating system has it's unique Java Virtual Machine (JVM) and the Java Runtime Environment (JRE). Support to Internet Protocols: Java has a rich variety of classes that abstracts the Internet protocols like HTTP, FTP, IP, TCP-IP, SMTP, DNS etc . Support to HTML: Most of the programming languages that are used for web application uses the html pages as a view to interact with the user. Java programming languages provide its support to html. Support to Java Reflection APIs: To map the functionalities, Java Reflection APIs provides the mechanism to retrieve the values from respective fields and accordingly creates the java objects. These objects enable to invoke methods to achieve the desired functionality. Support to XML parsing: Java has JAXP-APIs to read the xml data and create the xml document using different xml parsers like DOM and SAX. These APIs provides mechanism to share data among different applications over the internet. Support to Web Services : Java has a rich variety of APIs to use xml technology in diverse applications that supports N-Tiered Enterprise applications over the internet. Features like JAXB , JAXM, JAX-RPC , JAXR etc enables to implement web services in java applications. It makes java a most suited internet language. Support to java enabled Mobile devices: Java programming language is made in such a way so that it is compatible with mobile devices also. Java language also works with any java enabled mobile devices that support MIDP 1.0/2.0 including the Symbian OS mobile devices.
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 15
Features or Advantage of JDBC: Using JDBC you can send SQL and PL/SQL query to
database. JDBC is a java API for executing SQL statement and support basic SQL functionality.
JDBC Architecture : The JDBC API supports both two-tier and three-tier processing
models for database access.
1. Java code calls JDBC library 2. JDBC loads a driver 3. Driver talks to a particular database 4. Can have more than one driver -> more than one database 5. Ideal: can change database engines without changing any application code
exist for many Relational Database Management System (RDBMS) platforms. Type 1 driver needs to have the bridge driver installed and configured before JDBC can be used with it. These drivers are also known as JDBC ODBC Bridge Driver. Advantage The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available. Disadvantages
1. 2. 3. 4.
Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable. They are the slowest of all driver types. The client system requires the ODBC Installation to use the driver. Not good for the Web.
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 17
Loading Driver Establishing Connection Executing Statements Getting Results Closing Database Connection
1. Loading Driver: In this step of the jdbc connection process, we load the driver class by calling Class.forName(String DriverClassName) with the Driver class name as an argument. Once loaded, the Driver class creates an instance of itself. Syntax:
try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); //Or any other driver } catch(ClassNotFoundException e) { System.out.println( Unable to load the driver class! ); }
2. Establishing Connection: JDBC URL Syntax: jdbc: <subprotocol>: <subname> Each subprotocol has its own syntax for the source. Were using the jdbc odbc subprotocol, so the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver. The getConnection(String url, String username, String password) is a static method of getConnection(String password) DriverManager class. Which return a Connection class object. Syntax :
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. Syntax:
ResultSet: Looping the ResultSet: The next() method is used to successively step through the rows of the tabular results. Syntax: rs.next(); // rs instance of ResultSet;
5. Closing and Commiting Transaction : After task completion we should commit the transaction and then close the connection. Connection object provide two methods for performing these two tasks. Syntax:
OUTPUT :
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 21
Types of Applet : Applets are mainly categories into two types : Local Applet : The applets that are available on a machine and are tested and run on same
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 22
width = 200
height=200>
public class FirstApplet extends Applet { public void paint(Graphics g) { g.drawString("Hello World..!!!",25,50); } }
appletviewer FirstApplet.java or appletviewer TestApplet.html or Run TestApplet.html page using web browser
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 23
Methods Of Applet Class : Applet class provides all necessary support for applet execution, such as starting and stopping. It also provides methods that load and display images, and methods that load and play audio clips. Panel. Container, Applet extends the AWT class Panel In turn, Panel extends Container which extends Component. Component These classes provide support for Javas window-based, graphical interface. Thus, Applet provides all of the necessary support for window-based activities. public void init() - Called when an applet begins execution. It is the first method called for
any applet.
public void start() - Called by the browser when an applet should start (or resume)
will override this method if it needs to perform any cleanup prior to its destruction.
public void paint(Graphics g) - The paint( ) method is called each time your applets output
must be redrawn.
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 24
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 25
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 26
The Servlet Interface : All servlets must implement the Servlet interface. It declares the init( ) service( ) and ), ), destroy() destroy() methods that are called by the server during the life cycle of a servlet.
Developing Simple Servlet : STEP 1: Create and compile source code of Servlet : FirstServlet.java
import javax.servlet.*; public class FirstServlet implements Servlet { public void init(ServletConfig) { //Code Here For Initialization } public void service(ServletRequest req, ServletResponse res) throws IOException, ServletExcepion { PrintWriter out = res.getWriter(); out.println("<B>Hello World!!!</B>"); out.println("<BR>"); out.println("This is my first J2EE Web Application using Servlet."); out.close(); }
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 27
public void destroy() { //Code Here That is required when Servlet Object unload from container. } public String getServletInfo() { return "This is my First Servelt"; } public ServletConfig getServletConfig() { return null; } }//End Of FirstServlet class.
Open Tomcat configuration window from Program menu and then start tomcat or run startup.bat from the Tomcat installation directory.
STEP 3: Start Web Browser and request the FirstServlet Start a Web browser and enter the URL shown here:
http://localhost:8080/MyWebApp/FirstServlet
we can also write 127.0.0.1 in place of localhost.
http://127.0.0.1:8080/ MyWebApp/FirstServlet
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 28
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 29
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 30