0% found this document useful (0 votes)
6 views

JavaProgramming Unit-V

The document provides an overview of Java layout managers, detailing how they arrange components within containers, including BorderLayout, CardLayout, FlowLayout, GridLayout, and GridBagLayout. It also explains the lifecycle of applets, their execution methods, and contrasts applets with standalone applications. Key methods and examples for each layout manager and applet lifecycle are included to illustrate their usage.

Uploaded by

anudeepmolugu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

JavaProgramming Unit-V

The document provides an overview of Java layout managers, detailing how they arrange components within containers, including BorderLayout, CardLayout, FlowLayout, GridLayout, and GridBagLayout. It also explains the lifecycle of applets, their execution methods, and contrasts applets with standalone applications. Key methods and examples for each layout manager and applet lifecycle are included to illustrate their usage.

Uploaded by

anudeepmolugu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

UNIT-V

Chapter 1-Layout Managers

 Layout means the arrangement of components within the container.


 In other way we can say that placing the components at a particular position within the container.
 The task of lay outing the controls is done automatically by the Layout Manager.
 The layout manager automatically positions all the components within the container.
 If we do not use layout manager then also the components are positioned by the default layout manager(ex.
Default layout manager for applet is Flow Layout).

 To set Layout to any container we use

setLayout(new TypeLayout( )) method


ex: setLayout(new FlowLayout( ));

 To remove Layout to any container we use

setLayout(null) method

AWT Layout Manager Classes:

Sr. LayoutManager
No.

1
BorderLayout

The borderlayout arranges the components to fit in the five regions: east, west, north, south and center.

2
CardLayout

The CardLayout object treats each component in the container as a card. Only one card is visible at a time.(like stack)

3
FlowLayout

The FlowLayout is the default layout of an applet. It layouts the components in a directional flow.(i.e from Left to Right and
Top to Bottom)

4
GridLayout

The GridLayout manages the components in form of a rectangular grid.

5
GridBagLayout

This is the most flexible layout manager class. The object of GridBagLayout aligns the component vertically, horizontally or
along their baseline without requiring the components of same size. Using this we can perform alignment of a component
within a grid.
Constructors and Methods of Layout Manager Classes

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


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:


o BorderLayout(): creates a border layout but with no gaps between the components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between
the components

Example :

import java.awt.*;
import java.applet.*;
public class BorderLayoutExample extends Applet {
public void init () {
setLayout (new BorderLayout());
add(new Button("One"), BorderLayout.NORTH);
add(new Button("Two"), BorderLayout.WEST);
add(new Button("Three"), BorderLayout.CENTER);
add(new Button("Four"), BorderLayout.EAST);
add(new Button("Five"), BorderLayout.SOUTH);
add(new Button("Six"), BorderLayout.SOUTH);
}
}

Output :
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


1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER

Constructors of FlowLayout class

1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and vertical
gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given
horizontal and vertical gap.

Example :

import java.awt.*;
import java.applet.*;
public class FlowLayoutExample extends Applet {
public void init () {
// setLayout (new FlowLayout ()); // default
add (new Button ("One"));
add (new Button ("Two"));
add (new Button ("Three"));
add (new Button ("Four"));
add (new Button ("Five"));
add (new Button ("Six"));
}}
Output :

CardLayout :
 The CardLayout class manages the components(or containers) 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.
 This Layout arranges each card(container) in a stack order

Constructors of CardLayout class


1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.

Commonly used methods of CardLayout class

o public void next(Container parent): is used to flip to the next card of the given container.
o public void previous(Container parent): is used to flip to the previous card of the given container.
o public void first(Container parent): is used to flip to the first card of the given container.
o public void last(Container parent): is used to flip to the last card of the given container.
o public void show(Container parent, String name): is used to flip to the specified card with the given name

Example :

import java.awt.*;

import java.applet.*;

public class CardExample extends Applet {


CardLayout c = new CardLayout();
public void init () {

setLayout (c);
Panel pl = new Panel();
Panel pc = new Panel ();
Button b=new Button(“next”);
b.addActionListener(this);
List li=new List();
li.add(“Java”);
li.add(“DBMS”);
li.add(“OS”);
pl.add(li);
Choice ch=new Choice();
ch.add(“Java”);
ch.add(“DBMS”);
ch.add(“OS”);
pc.add(ch);
add(“List”,pl);
add(“Choice”,pc);
add ("NEXT", b);
}
public void actionPerformed(ActionEvent e) {
c.next(this);
}
}

GridLayout :
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each
rectangle(grid).

Constructors of GridLayout class


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, int hgap, int vgap): creates a grid layout with the given rows and columns
alongwith given horizontal and vertical gaps.

Example:
import java.awt.*;
import java.applet.*;
public class GridLayoutExample extends Applet {
public void init () {
setLayout(new GridLayout(2, 3));
add(new Button("One"));
add(new Button("Two"));
add(new Button("Three"));
add(new Button("Four"));
add(new Button("Five"));
}} output:
GridBagLayout :
 GridBagLayout class is used to align components vertically, horizontally or along their baseline.
 The components may not be of same size.
 Each GridBagLayout object maintains a dynamic, rectangular grid of cells.
 Each component occupies one or more cells known as its display area.
 Each component associates an instance of GridBagConstraints.
 With the help of constraints object we arrange component's display area on the grid.
 The GridBagLayout manages each component's minimum and preferred sizes in order to determine component's
size.

Constructor:

GridBagLayout()
Creates a grid bag layout manager.

 To use a GridBagLayout effectively, you must customize one or more of its components' GridBagConstraints.

Constraints:

gridx, gridy
Specifies the cell at the upper left of the component's display area, where the upper-left-most cell has address
gridx=0, gridy=0.

gridwidth, gridheight
Specifies the number of cells in a row (for gridwidth) or column (for gridheight) in the component's display area.
The default value is 1.
fill
Used when the component's display area is larger than the component's requested size to determine whether (and
how) to resize the component.
Valid values are
 GridBagConstraint.NONE (the default),
 GridBagConstraint.HORIZONTAL (make the component wide enough to fill its display area horizontally,
but don't change its height),
 GridBagConstraint.VERTICAL (make the component tall enough to fill its display area vertically, but
don't change its width), and
 GridBagConstraint.BOTH (make the component fill its display area entirely).
ipadx, ipady
Specifies the internal padding: how much to add to the minimum size of the component. The width of the
component will be at least its minimum width plus ipadx*2 pixels (since the padding applies to both sides of the
component). Similarly, the height of the component will be at least the minimum height plus ipady*2 pixels.
insets
Specifies the external padding of the component -- the minimum amount of space between the component and the
edges of its display area.
anchor
Used when the component is smaller than its display area to determine where (within the area) to place the
component. Valid values are
 GridBagConstraints.CENTER (the default),
 GridBagConstraints.NORTH,
 GridBagConstraints.NORTHEAST,
 GridBagConstraints.EAST,
 GridBagConstraints.SOUTHEAST,
 GridBagConstraints.SOUTH,
 GridBagConstraints.SOUTHWEST,
 GridBagConstraints.WEST, and
 GridBagConstraints.NORTHWEST.
weightx, weighty
Used to determine how to distribute space; this is important for specifying resizing behavior. Unless you specify a
weight for at least one component in a row (weightx) and column (weighty), all the components clump together in
the center of their container. This is because when the weight is zero (the default), the GridBagLayout puts any
extra space between its grid of cells and the edges of the container.

The following figure shows ten components (all buttons) managed by a GridBagLayout:

All the components have fill=GridBagConstraints.BOTH.

In addition, the components have the following non-default constraints:

 Button1, Button2, Button3: weightx=1.0


 Button4: weightx=1.0, gridwidth=GridBagConstraints.REMAINDER
 Button5: gridwidth=GridBagConstraints.REMAINDER
 Button6: gridwidth=GridBagConstraints.RELATIVE
 Button7: gridwidth=GridBagConstraints.REMAINDER
 Button8: gridheight=2, weighty=1.0,
 Button9, Button 10: gridwidth=GridBagConstraints.REMAINDER

import java.awt.*;
import java.util.*;
import java.applet.Applet;
public class GridBagEx1 extends Applet
{
protected void makebutton(String name,
GridBagLayout gridbag,
GridBagConstraints c) {
Button button = new Button(name);
gridbag.setConstraints(button, c);
add(button);
}
public void init() {
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();

setLayout(gridbag);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
makebutton("Button1", gridbag, c);
makebutton("Button2", gridbag, c);
makebutton("Button3", gridbag, c);

c.gridwidth = GridBagConstraints.REMAINDER; //end row


makebutton("Button4", gridbag, c);

c.weightx = 0.0; //reset to the default


makebutton("Button5", gridbag, c); //another row

c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last in row


makebutton("Button6", gridbag, c);

c.gridwidth = GridBagConstraints.REMAINDER; //end row


makebutton("Button7", gridbag, c);

c.gridwidth = 1; //reset to the default


c.gridheight = 2;
c.weighty = 1.0;
makebutton("Button8", gridbag, c);

c.weighty = 0.0; //reset to the default


c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.gridheight = 1; //reset to the default
makebutton("Button9", gridbag, c);
makebutton("Button10", gridbag, c);

resize(300, 100);
}
public static void main(String args[]) {
Frame f = new Frame("GridBag Layout Example");
GridBagEx1 ex1 = new GridBagEx1();

ex1.init();

f.add("Center", ex1);
f.pack();
f.resize(f.preferredSize());
f.show();
} }
Chapter 2-Applets
 Applet is a Java program that can be embedded into a web page.
 It runs inside the web browser and works at client side.
 Applet is embedded in a HTML page using the APPLET or OBJECT tag and hosted on a web server.
 All applets are sub-classes of java.applet.Applet class.
 Applets are not stand-alone programs. Instead, they run within either a web browser or an applet viewer.
 In general, execution of an applet does not begin at main() method. It has its own life cycle

Life cycle of an applet :

1. init( ) : The init( ) method is the first method to be called. This is where you should initialize variables.
This method is called only once during the run time of your applet.
2. start( ) : The start( ) method is called after init( ) to start the applet. It is also called to restart an applet after it
has been stopped.
3. paint( ) : The paint( ) method is called each time an AWT-based applet’s output must be drawn or
redrawn. paint( ) is also called when the applet begins execution. (note: paint() method is not life cycle
method of an applet)
4. stop( ) : The stop( ) method is called when the applet is closed
5. destroy( ) : The destroy( ) method is called when the environment determines that your applet needs to be
removed completely from memory.

Running Applet :
There are two ways to run an applet

1. By html file.
2. ByappletViewer tool

Example :

import java.applet.Applet;
import java.awt.Graphics;
/* <applet code="HelloWorld" width=200 height=60>
</applet> */
public class HelloWorld extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello World", 20, 20);
}
}
Running Applet by by appletviewer tool

c:\>javac HelloWorld.java
c:\>appletviewer HelloWorld.java

Running Applet by html file:


Step 1 : To execute the applet by html file, create an applet and compile it.
c:\>javac HelloWorld.java

Step 2 :After that create an html file and place the applet code in html file.
<html>
<body>
<applet code=" HelloWorld " width="300" height="300">
</applet>
</body>
</html>

Step 3: Run the Html file in the browser

Example : Demonstrating Life Cycle methods of an applet

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;
/*<applet code="AppletLifeCycle.class" width="350" height="150"> </applet>*/
public class AppletLifeCycle extends Applet
{
public void init()
{
setBackground(Color.CYAN);
System.out.println("init() called");
}
public void start(){ System.out.println("Start() called"); }
public void paint(Graphics g){ g.drawString(“hello”,100,100); }
public void stop() { System.out.println("Stop() Called"); }
public void destroy() { System.out.println("Destroy)() Called"); }
}
Applet vs Application

Applet Application

An applet is a form of Java program An application is a standalone Java


which is embedded with HTML page program which can be run
and loaded by a web server to be run on independently on client/server without
a web browser. the need of a web browser.
There is no requirement of main() The execution of the program starts
method for the execution of the from the main() method.
program it starts with init() method
Applet doesn’t have access to the local Application can access local disk files/
network files and folders. folders and network system.
It must run within GUI. It doesn’t require any Graphical User
Interface (GUI).
An applet doesn’t have access to local An application can perform read and
files and so cannot perform read and write operations on files stored on the
write operations on files stored on local local disk.
disk.

Parameters passing to Applet


o We can get any information from the HTML file as a parameter.
o For this purpose, Applet class provides a method named getParameter( ).
o We use <param> tag with name value attributes

Syntax:

public String getParameter(String parameterName)

Example of using parameter in Applet:


<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>

import java.applet.Applet;
import java.awt.Graphics;

public class UseParam extends Applet{

public void paint(Graphics g){


String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
OUTPUT :
Applet displays Welcome to applet
Chapter 3-JDBC (Java Database Connectivity)
o JDBC is a Java API to connect and execute the query with the database.
o It is a part of JavaSE (Java Standard Edition).
o JDBC API uses JDBC drivers to connect with the database.

The java.sql package contains classes and interfaces for JDBC API.

interfaces of JDBC API

o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface

classes of JDBC API are

o DriverManager class
o Blob class
o Clob class
o Types class

JDBC DRIVERS
JDBC Driver is a software component that enables java application to interact with the database. There are 4
types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge
driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin
driver.
2) Native-API driver

The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls
into native calls of the database API. It is not written entirely in java.

3) Network Protocol driver

The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. It is fully written in java.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is
known as thin driver. It is fully written in Java language.

JDBC Process

1. Register for Driver


2. Connect to the database
3. Execute queries and update statements to the database
4. Retrieve the result received from the database.

Example 1 : Jdbc & mysql to display employee id and name from employee
table import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/xx","root","root");
//here xx is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}}

OUTPUT : Displays employee ids and names from emp table of mysql

Example 2 : To insert records into a database


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class InsertDataDemo {


public static void main(String[] args) {
Connection connection = null;
Statement stmt = null;
try
{

Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/JDBCDemo", "root", "password");

stmt = connection.createStatement();
stmt.execute("INSERT INTO EMPLOYEE (ID,FIRST_NAME,LAST_NAME,STAT_CD) "
+ "VALUES (1,'Lokesh','Gupta',5)");
}
catch (Exception e) {
e.printStackTrace();
}finally {
try {
stmt.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

OUTPUT : Inserts a record into employee table.

JDBC Statement objects

 Once a connection is obtained we can interact with the database.


 The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and
properties that enable you to send SQL or PL/SQL commands and receive data from your database.

The following table provides a summary of each interface's purpose to decide on the interface to use.

Recommended Use
Use this for general-purpose access to your database. Useful when you are using
Statement
static SQL statements at runtime. The Statement interface cannot accept parameters.
Use this when you plan to use the SQL statements many times. The
PreparedStatement
PreparedStatement interface accepts input parameters at runtime.
Use this when you want to access the database stored procedures. The
CallableStatement
CallableStatement interface can also accept runtime input parameters.

1) The Statement Object

Creating Statement Object

Statement stmt = null;


try {
stmt = conn.createStatement( );
. . .}
catch (SQLException e) {
. . . }
 Once you've created a Statement object, you can then use it to execute an SQL statement with one of its

three execute methods.

 boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can be retrieved; otherwise,
it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL.
 int executeUpdate (String SQL): Returns the number of rows affected by the execution of the SQL statement.
Use this method to execute SQL statements for which you expect to get a number of rows affected - for example,
an INSERT, UPDATE, or DELETE statement.
 ResultSet executeQuery (String SQL): Returns a ResultSet object. Use this method when you expect to get a
result set, as you would with a SELECT statement.

2) The PreparedStatement Object

The PreparedStatement interface extends the Statement interfaceThis statement gives you the flexibility of

supplying arguments dynamically.

Creating PreparedStatement Object


PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
. . .
}
catch (SQLException e) {
. . .
}

 All parameters in JDBC are represented by the ? symbol, you must supply values for every parameter before
executing the SQL statement.
 The setXXX() methods bind values to the parameters, where XXX represents the Java data type of the value
you wish to bind to the input parameter. If you forget to supply the values, you will receive an SQLException.
 Each parameter marker is referred by its ordinal position. The first marker represents position 1, the next
position 2, and so forth. This method differs from that of Java array indices, which starts at 0.
 All of the Statement object's methods for interacting with the database (a) execute(), (b) executeQuery(), and
(c) executeUpdate() also work with the PreparedStatement object.

Example :
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");

con.close();

}catch(Exception e){ System.out.println(e);

}}}

3) The CallableStatement Object

 It is used to execute a call to a database stored procedure.

Creating CallableStatement Object:


CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName ()}";
cstmt = conn.prepareCall (SQL);
. . .
}
catch (SQLException e) {} . . .
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy