Java Unit V
Java Unit V
UNIT-V
AWT Controls & Database Connectivity
AWT
AWT ( ‘Abstract window Toolkit’) is an API to develop GUI or window-
based applications in java.
Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system.
The java.awt package provides classes for AWT api such as TextField,
Label,TextArea, RadioButton, CheckBox, Choice, List etc.
CONTAINER:
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The containers are Frame, Dialog and Panel.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
public void setSize(int width,int sets the size (width and height) of the
height) component.
EX:
import java.awt.*;
import java.awt.event.*;
class framedemo
{
public static void main(String[] args)
SITA1301 JAVA PROGRAMMING
2
{
Frame f=new Frame("my first frame");
f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
E:\javapgms>javac framedemo.java
E:\javapgms>java framedemo
Output
LABEL
label is an object of type Label, and it contains a string, which it displays.
Labels are passive controls that do not support any interaction with the user.
Label defines the following constructors:
Label( ):
Ex:
Label(String str)
Ex:
Methods
Void setText(String str);
String getText();
void setAlignment(int how)
int getAlignment( )
It has no Listener Class.
Ex:
import java.awt.*;
import java.awt.event.*;
class label
{
public static void main(String[] args)
{
Frame f=new Frame("first");
Label l1=new Label("Name");
Label l2=new Label("age");
Label l3=new Label("gender");
l1.setBounds(100,50,70,30);
l2.setBounds(100,100,70,30);
l3.setBounds(100,120,70,30);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}});
f.add(l1);
f.add(l2);
f.add(l3);
f.setSize(300,300);
f.setVisible(true);
f.setLayout(null);
}
}
E:\javapgms>javac label.java
E:\javapgms>java label
Output
TEXTFIELD
The TextField class implements a single-line text-entry area, usually called an
edit control.
Text fields allow the user to enter strings and to edit the text using the arrow
keys, cut and paste keys, and mouse selections.
TextField is a subclass of TextComponent.
TextField(int numchars)
TextField(String str):
METHODS
String getText();
Void setText(“hello”)
setBackground(Color.red)
getBackground()
getSelectedText()
EVENT
ActionListener()
METHOD
Void actionPerformed(ActionEvent e)
{
}
Ex:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class textfield implements ActionListener
{
Frame f=new Frame();
Label l1,l2;
TextField t1,t2,t3;
textfield()
{
l1=new Label("Name :",Label.LEFT);
l2=new Label("Password:",Label.LEFT);
t1=new TextField(15);
t2=new TextField(15);
t2.setEchoChar('?');
t3=new TextField(40);
l1.setBounds(100,100,100,20);
l2.setBounds(100,200,100,20);
t1.setBounds(250,100,150,20);
t2.setBounds(250,200,150,20);
t3.setBounds(50,300,400,20);
f.add(l1);
f.add(l2);
f.add(t1);
f.add(t2);
f.add(t3);
t1.addActionListener(this);
t2.addActionListener(this);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
BUTTON
Button(String str)
METHODS
setLabel():After a button has been created, you can set its label by calling setLabel( ).
getLabel( ):
You can retrieve its label by calling getLabel( ).
Interface
ActionListener
Method
Object.addActionListener(this);
Public void actionPerformed(ActionEvent e)
{
}
Ex:
Simple Button
import java.awt.*;
import java.awt.event.*;
public class firstbutton
{
public static void main(String[] args)
{
Frame f=new Frame("buttonexample");
final TextField tf=new TextField();
tf.setBounds(50,50,150,200);
Button b=new Button("yes");
b.setBounds(50,100,60,30);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
tf.setText("clicked yes");
}
});
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.add(b);
f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
E:\javapgms>javac firstbutton.java
E:\javapgms>java firstbutton
Button Array
Ex:
import java.awt.*;
import java.awt.event.*;
public class buttonlist implements ActionListener
{
String s="";
Button y
public void init()
{
Button yes=new Button("yes");
Button no=new Button("no");
Button maybe=new Button("decided");
b[0]=(Button) add(yes);
b[1]=(Button) add(no);
b[2]=(Button) add(maybe);
for(int i=0;i<3;i++)
{
b[i].addActionListener(this);
}
}
public void actionPerformed(ActionEvent e)
{
for( int i=0;i<3;i++)
{
if(e.getSource()==b[i])
{
s="you pressed"+b[i].getLabel();
}
}
repaint();
}
public void paint(Graphics g)
{
g.drawString(s,6,100);
}
}
CHECKBOX
Checkbox( ):
Checkbox(String str):
METHODS
boolean getState( )
void setState(boolean on)
String getLabel( )
void setLabel(String str)
getSource()
INTERFACE
ItemListener
METHOD
addItemListener(this);
Ex:
import java.awt.*;
import java.awt.event.*;
public class checkbox implements ItemListener
{
Frame f;
Checkbox Win98, winNT, solaris, mac;
TextField tf;
checkbox()
{
f=new Frame("checkbox");
tf=new TextField();
tf.setBounds(100,300,200,20);
Win98 = new Checkbox("win98");
Win98.setBounds(100,100,70,30);
winNT = new Checkbox("winNT");
winNT.setBounds(100,150,70,30);
solaris = new Checkbox("Solaris");
solaris.setBounds(100,200,70,30);
mac = new Checkbox("Mac");
mac.setBounds(100,250,70,30);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
Win98.addItemListener(this);
winNT.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
f.add(Win98);
f.add(winNT);
f.add(solaris);
f.add(mac);
f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
tf.setText(winNT.getLabel()+" "+winNT.getState());
}
if(e.getSource()==solaris)
{
tf.setText(solaris.getLabel()+" "+solaris.getState());
}
if(e.getSource()==mac)
{
tf.setText(mac.getLabel()+" "+mac.getState());
}
}
public static void main(String[] args)
{
new checkbox();
}
}
E:\javapgms>javac checkbox.java
E:\javapgms>java checkbox
CHECKBOX GROUP
It is possible to create a set of mutually exclusive check boxes in which one and only
one
check box in the group can be checked at any one time
Ex:
import java.awt.*;
import java.awt.event.*;
public class checkboxgroup
{
public static void main(String[] args)
{
Frame f=new Frame("checkbox");
boolean b;
CheckboxGroup gp=new CheckboxGroup();
Checkbox Win98, winNT, solaris, mac;
Win98 = new Checkbox("Windows 98/XP", gp, true);
Win98.setBounds(100,100,50,50);
winNT = new Checkbox("Windows NT/2000",gp,false);
winNT.setBounds(100,150,50,50);
solaris = new Checkbox("Solaris",gp,true);
solaris.setBounds(100,200,50,50);
mac = new Checkbox("MacOS",gp,false);
mac.setBounds(100,250,50,50);
/*Win98.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
b=Win98.getState();
}
});
winNT.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
str=winNT.getState();
tf.setText(str);
}
});
solaris.addItemListener(new ItemListener()
{
E:\javapgms>javac checkboxgroup.java
E:\javapgms>java checkboxgroup
LIST
List( )
The first version creates a List control that allows only one item to be selected at any one time
List(int numRows)
In the second form, the value of numRows specifies the number of entries in the list that will
always be visible (others can be scrolled into view as needed).
In the third form, if multipleSelect is true, then the user may select two or more items at a
time.If it is false, then only one item may be selected.
Ex:
import java.awt.*;
import java.awt.event.*;
public class list
{
public static void main(String[] args)
{
Frame f=new Frame();
E:\javapgms>javac list.java
E:\javapgms>java list
TEXT AREA
TextArea( )
TextArea(String str)
METHODS
getText( )
setText( )
getSelectedText( )
select( ),
isEditable( )
setEditable( )
Ex:
import java.awt.*;
import java.awt.event.*;
public class TextAreaDemo {
public static void main(String[] args)
{
Frame f=new Frame();
String val = "There are two ways of constructing " +
"a software design.\n" +
"One way is to make it so simple\n" +
"that there are obviously no deficiencies.\n" +
"And the other way is to make it so complicated\n" +
"that there are no obvious deficiencies.\n\n" +
" -C.A.R. Hoare\n\n" +
"There's an old story about the person who wished\n" +
"his computer were as easy to use as his telephone.\n" +
"That wish has come true,\n" +
"since I no longer know how to use my telephone.\n\n" +
" -Bjarne Stroustrup, AT&T, (inventor of C++)";
TextArea text = new TextArea();
text.setBounds(100,100,200,200);
text.setText(val);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.add(text);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
E:\javapgms>javac TextAreaDemo.java
E:\javapgms>java TextAreaDemo
SCROLLBAR
Scroll bars are used to select continuous values between a specified minimum and
maximum.
Scroll bars may be oriented horizontally or vertically.
A scroll bar is actually a composite of several individual parts.
Each end has an arrow that you can click to move the current value of the scroll bar
one unit in the direction of the arrow.
The current value of the scroll bar relative to its minimum and maximum values is
indicated by the slider box (or thumb) for the scroll bar.
Scrollbar( )
Scrollbar(int style)
Scrollbar(int style, int initialValue , int thumbSize, int min, int max)
METHODS
int getValue( )
void setValue(int newValue)
int getMinimum( )
int getMaximum( )
INTERFACE
AdjustmentListener interface
OBJECT
AdjustmentEvent
EVENT METHOD
public void getAdjustmentType( )
{}
Ex:
import java.awt.*;
import java.awt.event.*;
public class SBDemo implements AdjustmentListener
{
String msg = "";
Frame f;
Scrollbar vertSB, horzSB;
Label l;
SBDemo()
{
f=new Frame();
l=new Label();
l1=new Label();
l2=new Label();
vertSB = new Scrollbar(Scrollbar.VERTICAL,0, 1, 0, 30);
horzSB = new Scrollbar(Scrollbar.HORIZONTAL,0, 1, 0, 30);
vertSB.setBounds(100,100,50,100);
horzSB.setBounds(200,100,200,50);
l.setSize(200,200);
vertSB.addAdjustmentListener(this);
horzSB.addAdjustmentListener(this);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.add(vertSB);
f.add(horzSB);
f.add(l);
f.setSize(450,450);
f.setVisible(true);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
if(e.getSource()==vertSB)
E:\javapgms>javac SBDemo.java
E:\javapgms>java SBDemo
LAYOUT MANAGERS
Types
1.FlowLayout
2.GridLayout
3.BorderLayout
FlowLayout
FlowLayout( )
The first form creates the default layout, which centers components and leaves five
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class flowlayout implements ActionListener
{
Frame f=new Frame();
Label l1,l2,l3;
TextField t1,t2,t3;
Button Add=new Button("add");
flowlayout()
{
l1=new Label("ist value");
l2=new Label("2nd value");
l3=new Label("result");
t1=new TextField(15);
t2=new TextField(15);
t3=new TextField();
l1.setBounds(100,100,70,70);
l2.setBounds(100,150,70,70);
l3.setBounds(100,200,70,70);
t1.setBounds(250,100,70,70);
t2.setBounds(250,200,70,70);
t3.setBounds(250,300,70,70);
Add.setBounds(200,400,70,70);
f.setLayout(new FlowLayout(FlowLayout.LEFT));
f.add(l1);
f.add(l2);
f.add(l3);
f.add(t1);
f.add(t2);
f.add(t3);
f.add(Add);
Add.addActionListener(this);
/*Add.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int i=Integer.parseInt(t1.getText());
int j=Integer.parseInt(t2.getText());
int c=0;
if(e.getSource()==Add)
{
c=i+j;
}
t3.setText(String.valueOf(c));
}
});*/
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
}
E:\javapgms>javac flowlayout.java
E:\javapgms>java flowlayout
BorderLayout
The BorderLayout class implements a common layout style for top-level windows.
It has four narrow, fixed-width components at the edges and one large area in the
center.
The four sides are referred to as north, south, east, and west. The middle area is called
the center.
BorderLayout( )
It allows you to specify the horizontal and vertical space left between components in
BorderLayout.CENTER BorderLayout.SOUTH
BorderLayout.EAST BorderLayout.WEST
BorderLayout.NORTH
add():
It is used to add the components which is defined by Container:
void add(Component compObj, Object region);
Here, compObj is the component to be added, and region specifies where the
component will be added.
Ex:
import java.awt.*;
import java.awt.event.*;
public class borderlayout {
Frame f;
String msg="";
borderlayout()
{
f=new Frame("BorderLayout");
f.setLayout(new BorderLayout());
Button b1=new Button("north");
Button b2=new Button("south");
Button b3=new Button("east");
Button b4=new Button("west");
f.add(b1,BorderLayout.SOUTH);
f.add(b2,BorderLayout.NORTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
msg = "The reasonable man adapts " +
"himself to the world;\n" +
"the unreasonable one persists in " +
"trying to adapt the world to himself.\n" +
"Therefore all progress depends " +
"on the unreasonable man.\n\n" +
" - George Bernard Shaw\n\n";
f.add(new TextArea(msg), BorderLayout.CENTER);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args)
{
new borderlayout();
}
}
GridLayout
When you instantiate a GridLayout, you define the number of rows and columns.
GridLayout( )
The second form creates a grid layout with the specified number of rows and columns.
It specify the horizontal and vertical space left between components in horz and vert,
unlimited-length rows.
Ex:
import java.awt.*;
import java.awt.event.*;
public class gridlayout {
Frame f;
final int n = 3;
TextField tf;
gridlayout()
{
f=new Frame("");
f.setLayout(new BorderLayout());
f.setLayout(new GridLayout(n, n));
tf=new TextField();
f.setFont(new Font("SansSerif", Font.BOLD, 24));
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
int k = i * n + j;
if(k >=0)
f.add(new Button("" + k));
}
}
f.add(new Button("+"));
f.add(new Button("-"));
f.add(new Button("*"));
f.add(new Button("/"));
f.add(new Button("="));
f.add(tf,BorderLayout.NORTH);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.setSize(200,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new gridlayout();
}
}
A menu bar displays a list of top-level menu choices. Each choice is associated with a drop-
down menu.
Menu Classes
To create a menu bar, first create an instance of MenuBar. This class only defines the default
constructor. Next, create instances of Menu that will define the selections displayed on the bar.
1. MenuBar
2. Menu
3. MenuItem
MenuItem( )
MenuItem(String itemName )
Once you have created a menu item, you must add the item to a Menu object by
using add( ).The general form is
Menuobject.add(MenuItemobject)
Here, item is the item being added. Items are added to a menu in the order in which the
calls to add( ) take place. The item is returned.
Menubarobject. add(Menuobject)
Here, menu is the menu being added. The menu is returned.
Ex:
import java.awt.*;
import java.awt.event.*;
public class menudesign implements ActionListener
{
Frame f;
TextArea te;
MenuBar mb;
MenuItem New,Save,Cut,Copy,Paste,Close;
menudesign()
{
f=new Frame();
te=new TextArea();
New=new MenuItem("New");
Save=new MenuItem("Save");
Cut=new MenuItem("Cut");
Copy=new MenuItem("Copy");
Paste=new MenuItem("Paste");
Close=new MenuItem("Close");
//New.addActionListener(this);
//Save.addActionLitener(this);
Cut.addActionListener(this);
Copy.addActionListener(this);
Paste.addActionListener(this);
Close.addActionListener(this);
mb=new MenuBar();
fi.add(New);
fi.add(Save);
ed.add(Cut);
ed.add(Copy);
ed.add(Paste);
ex.add(Close);
te.setBounds(50,50,100,200);
//ta.setBackground(Color.cyan);
mb.add(fi);
mb.add(ed);
mb.add(fo);
mb.add(ex);
f.setMenuBar(mb);
f.add(te);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.setSize(200,300);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String s=(String)e.getActionCommand();
if(s.equals("Cut"))
//te.Cut();
te.setText(s);
if(s.equals("Paste"))
//te.Paste();
te.setText(s);
if(s.equals("Copy"))
//te.Copy();
te.setText(s);
if(s.equals("Close"))
System.exit(0);
}
public static void main(String[] args)
{
new menudesign();
}
}
Database Connectivity
• ODBC driver –
It require a driver to be loaded at runtime to connect to any data source.
The driver is implemented as a class that is located and loaded at runtime.
The ODBC driver for JDBC connections is named sun.java.odbc.JdbcOdbcDriver.
It require an ODBC connection string to connect to the data source.
To connect with an ODBC DSN, we require a connection string "jdbc:odbc:ODBC DSN
String"
The package containing the database related classes is contained in java.sql.
Dynamically load the class sun.java.odbc.JdbcOdbcDriver as
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(database, "", "");
The Statement must be created to execute a SQL query on the opened database.
Statement s = conn.createStatement();
To clean up after we are done with the SQL query, • To call s.close() to dispose the
object Statement.
• To call conn.close() for close the database
Step 1 : Open Microsoft Access and select Student data base option and give the data
base name as File name option as “student”
Step 2 : Create a table and insert your data into the table
Step 3 : Save the table with the desired name; in this article we save the following
records with the table name student.
37120001 Aravind
37120002 Arjun
• Now Creating DSN of your data base –
Step 4 : Open your Control Panel and than select Administrative Tools.
Step 5 : Click on Data Source(ODBC)-->User DSN.
Step 6 : Now click on add option for making a new DSN.select Microsoft Access Driver (*.mdb.
*.accdb) and than click on Finish
Step 7 : Make your desired Data Source Name and then click on the Select option.
Step 8 : Now you select your data source file for storing it and then click ok and then click on
Create and Finish
Example
import java.sql.*;
class DatabaseDemo
{
public static void main(String ar[])
{
Try
{
String url="jdbc:odbc:veeradsn";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
st.executeUpdate("INSERT into std(Reg_no,Name) values("+37120003+",'Avinash'"+")");
ResultSet rs=st.executeQuery("select * from std");
while(rs.next())
System.out.println(rs.getString(1)+ " "+rs.getString("Name"));
}
catch(Exception ee)
{
System.out.println(ee);
}
}
}