JavaProgramming Unit-V
JavaProgramming Unit-V
setLayout(null) method
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
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.
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.
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
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.*;
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).
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:
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);
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
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
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>
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
Syntax:
import java.applet.Applet;
import java.awt.Graphics;
The java.sql package contains classes and interfaces for 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
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)
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.
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
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
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();
}
}
}
}
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.
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.
The PreparedStatement interface extends the Statement interfaceThis statement gives you the flexibility of
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();
}}}