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

Java Unit V

The document discusses various AWT controls including labels, buttons, checkboxes, text fields, frames, and containers. It provides code examples for creating each type of control and handling events. It also covers establishing a database connection using JDBC and performing operations like creating tables and inserting/updating data.

Uploaded by

rajachauhan1234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Java Unit V

The document discusses various AWT controls including labels, buttons, checkboxes, text fields, frames, and containers. It provides code examples for creating each type of control and handling events. It also covers establishing a database connection using JDBC and performing operations like creating tables and inserting/updating data.

Uploaded by

rajachauhan1234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

1

UNIT-V
AWT Controls & Database Connectivity

Control Fundamentals- Labels-Buttons-Checkboxes-Checkboxgroup-Lists-Scroll bars-Textfield-


TextArea-Layout Managers-Flow layout-Card layout-Grid layout-Border layout-Menus
JDBC Connectivity - Introduction –Establishing Connection – Creation of Database Tables –
Entering Data into the Tables- Table Updating .

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.

METHODS OF COMPONENT CLASS


Method Description

public void add(Component c) inserts a component on this component.

public void setSize(int width,int sets the size (width and height) of the
height) component.

public void defines the layout manager for the


setLayout(LayoutManager m) component.

public void setVisible(boolean changes the visibility of the component,


status) by default false.

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:

Label(String str, int how)


Ex:
SITA1301 JAVA PROGRAMMING
3

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

SITA1301 JAVA PROGRAMMING


4

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 defines the following constructors:


The first version creates a default text field.
Textfield():
Ex:

TextField(int numchars)

TextField(String str):

TextField(String str, int numChars)

METHODS
String getText();
Void setText(“hello”)
setBackground(Color.red)
getBackground()
getSelectedText()

EVENT
ActionListener()

METHOD
Void actionPerformed(ActionEvent e)
{
}

SITA1301 JAVA PROGRAMMING


5

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)
{

t3.setText(t1.getText()+" "+t2.getText()+" "+"selected text is"+t1.getSelectedText());


}
public static void main(String[] arg)
{
new textfield();
}
}

SITA1301 JAVA PROGRAMMING


6

BUTTON

 The most widely used control is the push button.


 A push button is a component that contains a label and that generates an event when it
is pressed.
 Push buttons are objects of type Button.

Button defines these two constructors:


Button( ):

It creates an empty button.

Button(String str)

SITA1301 JAVA PROGRAMMING


7

It creates a button that contains str as a label.

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");

SITA1301 JAVA PROGRAMMING


8

}
});
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()

SITA1301 JAVA PROGRAMMING


9

{
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);
}
}

SITA1301 JAVA PROGRAMMING


10

CHECKBOX

 A check box is a control that is used to turn an option on or off.


 It consists of a small box that can either contain a check mark or not.
 There is a label associated with each check box that describes what option the box
represents.
 You change the state of a check box by clicking on it.
 Check boxes can be used individually or as part of a group.
 Checkboxes are objects of the Checkbox class.

Checkbox supports these constructors:

Checkbox( ):

Checkbox(String str):

Checkbox(String str, boolean on)

METHODS

boolean getState( )
void setState(boolean on)
String getLabel( )
void setLabel(String str)
getSource()

INTERFACE

ItemListener

METHOD

addItemListener(this);

public void itemStateChanged(ItemEvent e)


{
}

Ex:

SITA1301 JAVA PROGRAMMING


11

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);
}

public void itemStateChanged(ItemEvent e)


{
if(e.getSource()==Win98)
{
tf.setText("you pressed"+" "+Win98.getLabel()+" "+Win98.getState());
}
if(e.getSource()==winNT)
{

SITA1301 JAVA PROGRAMMING


12

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

SITA1301 JAVA PROGRAMMING


13

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()
{

SITA1301 JAVA PROGRAMMING


14

public void itemStateChanged(ItemEvent e)


{
tf.setText(solaris.getState());
}
});
mac.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
tf.setText(mac.getState());
}
});*/
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.add(Win98);
f.add(winNT);
f.add(solaris);
f.add(mac);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

E:\javapgms>javac checkboxgroup.java

E:\javapgms>java checkboxgroup

SITA1301 JAVA PROGRAMMING


15

LIST

 The List class provides a compact, multiple-choice, scrolling selection list.


 a List object can be constructed to show any number of choices in the visible window.
 It can also be created to allow multiple selections.

List provides these constructors:

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).

List(int numRows, boolean multipleSelect)

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();

SITA1301 JAVA PROGRAMMING


16

final Label l=new Label();


l.setAlignment(Label.CENTER);
l.setSize(500,100);
Button b=new Button("show");
b.setBounds(200,150,80,30);
final List os=new List(4,false);
os.setBounds(100,100,70,70);
os.add("windows");
os.add("linux");
os.add("unix");
os.add("android");
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String data="os selected"+os.getItem(os.getSelectedIndex());
l.setText(data);
}});
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.add(os);
f.add(l);
f.add(b);
f.setSize(450,450);
//f.setLayout(null);
f.setVisible(true);
}
}

E:\javapgms>javac list.java

E:\javapgms>java list

SITA1301 JAVA PROGRAMMING


17

TEXT AREA

AWT includes a simple multiline editor called TextArea.

Following are the constructors for TextArea:

TextArea( )

TextArea(int numLines, int numChars)

TextArea(String str)

TextArea(String str, int numLines, int numChars)

TextArea(String str, int numLines, int numChars, int sBars)

METHODS
getText( )
setText( )
getSelectedText( )
select( ),
isEditable( )
setEditable( )

SITA1301 JAVA PROGRAMMING


18

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

SITA1301 JAVA PROGRAMMING


19

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 defines the following constructors:

Scrollbar( )

It creates a vertical scroll bar.

Scrollbar(int style)

It allows you to specify the orientation of the scroll bar.

Scrollbar(int style, int initialValue , int thumbSize, int min, int max)

If style is Scrollbar.VERTICAL, a vertical scroll bar is created. If style is


Scrollbar.HORIZONTAL, the scroll bar is horizontal

SITA1301 JAVA PROGRAMMING


20

METHODS

int getValue( )
void setValue(int newValue)
int getMinimum( )

int getMaximum( )

void setUnitIncrement(int newIncr)

void setBlockIncrement(int newIncr)

INTERFACE

AdjustmentListener interface

OBJECT

AdjustmentEvent

EVENT METHOD
public void getAdjustmentType( )
{}

The types of adjustment events are as follows:


BLOCK_DECREMENT -A page-down event has been generated.
BLOCK_INCREMENT -A page-up event has been generated.
TRACK -An absolute tracking event has been generated.
UNIT_DECREMENT -The line-down button in a scroll bar has been pressed.
UNIT_INCREMENT -The line-up button in a scroll bar has been pressed.

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);

SITA1301 JAVA PROGRAMMING


21

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)

l.setText("Vertical Scrollbar value is:"+e .getValue());


else
l.setText("Horizontal Scrollbar value is:"+e .getValue());
}

public static void main(String[] args)


{
new SBDemo();
}
}

E:\javapgms>javac SBDemo.java

E:\javapgms>java SBDemo

SITA1301 JAVA PROGRAMMING


22

LAYOUT MANAGERS

 A layout manager is an instance of any class that implements the LayoutManager


interface.
 The layout manager is set by the setLayout( ) method. If no call to setLayout( ) is
made, then the default layout manager is used. Whenever a container is resized (or
sized for the first time), the layout manager is used to position each of the components
within it.

The setLayout( ) method has the following general form:


void setLayout(LayoutManager layoutObj)

Types
1.FlowLayout
2.GridLayout
3.BorderLayout

FlowLayout

 FlowLayout is the default layout manager.


 It implements a simple layout style, which is similar to how words flow in a text editor.
Components are laid out from the upper-left corner, left to right and top to bottom.
 When no more components fit on a line, the next one appears on the next line.
 A small space is left between each component, above and below, as well as left and
right.

Constructors for FlowLayout:

FlowLayout( )
The first form creates the default layout, which centers components and leaves five

SITA1301 JAVA PROGRAMMING


23

pixels of space between each component.


FlowLayout(int how)
The second form lets you specify how each line is aligned. Valid values for how are as
follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
These values specify left, center, and right alignment, respectively.

FlowLayout(int how, int horz, int vert)


The third form allows you to specify the horizontal and vertical space left between
components in horz and vert, respectively.
Ex:

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)

SITA1301 JAVA PROGRAMMING


24

{
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);
}

public void actionPerformed(ActionEvent e)


{
String s1=t1.getText();
String s2=t2.getText();
int i=Integer.parseInt(s1);
int j=Integer.parseInt(s2);
int c=0;
if(e.getSource()==Add)
{
c=i+j;
}
String re=String.valueOf(c);
t3.setText(re);
}

public static void main(String[] arg)


{
new flowlayout();
}
}

E:\javapgms>javac flowlayout.java

E:\javapgms>java flowlayout

SITA1301 JAVA PROGRAMMING


25

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.

Constructors for BorderLayout:

BorderLayout( )

It creates a default border layout.

BorderLayout(int horz, int vert)

It allows you to specify the horizontal and vertical space left between components in

horz and verz

BorderLayout defines the following constants that specify the regions:

BorderLayout.CENTER BorderLayout.SOUTH
BorderLayout.EAST BorderLayout.WEST
BorderLayout.NORTH

SITA1301 JAVA PROGRAMMING


26

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();
}
}

SITA1301 JAVA PROGRAMMING


27

GridLayout

 GridLayout lays out components in a two-dimensional grid.

 When you instantiate a GridLayout, you define the number of rows and columns.

Constructors for GridLayout

GridLayout( )

The first form creates a single-column grid layout

GridLayout(int numRows, int numColumns )

The second form creates a grid layout with the specified number of rows and columns.

GridLayout(int numRows, int numColumns, int horz, int vert)

It specify the horizontal and vertical space left between components in horz and vert,

respectively. Either numRows or numColumns can be zero. Specifying numRows as zero

allows for unlimited-length columns. Specifying numColumns as zero allows for

unlimited-length rows.

Ex:

SITA1301 JAVA PROGRAMMING


28

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();
}
}

SITA1301 JAVA PROGRAMMING


29

MENU BARS AND MENUS

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

Constructors for MenuItem:

MenuItem( )

MenuItem(String itemName )

MenuItem(String itemName, MenuShortcut keyAccel)

Constructors for Menu:


Menu( )
Menu(String optionName )
Menu(String optionName , boolean removable )

SITA1301 JAVA PROGRAMMING


30

Add Menuitem to Menu

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.

Add Menu to Menubar


Once you have added all items to a Menu object, you can add that object to the menu
bar by using this version of add( ) defined by MenuBar:

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();

SITA1301 JAVA PROGRAMMING


31

Menu fi=new Menu("File");


Menu ed=new Menu("Edit");
Menu fo=new Menu("Format");
Menu ex=new Menu("exit");

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)
{

SITA1301 JAVA PROGRAMMING


32

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.

• ODBC connection string

SITA1301 JAVA PROGRAMMING


33

• Import the classes to connect to the database


• Load the JDBC:ODBC driver
• Open the MS-Access database file in the application space
• Create a Statement object to execute the SQL query
• Cleanup after finishing the job
• Creating a Database

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);
}
}
}

SITA1301 JAVA PROGRAMMING

You might also like