Adv. Java Lab Manual

137
1 ROHIT BHATIA Advance Java. 08-CSE-133 Practical No: - 1 Aim: - Write a Program To Find Maximum of two numbers.

description

Advance Java Program

Transcript of Adv. Java Lab Manual

Page 1: Adv. Java Lab Manual

1

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 1

Aim: - Write a Program To Find Maximum of two numbers.

Page 2: Adv. Java Lab Manual

2

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.io.*;

import java.util.*;

import java.math.*;

public class Maxof2{

public static void main(String args[])throws IOException{

int[] x=new int[1];

int[] y=new int[1];

BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter first no.:");

x[0]=Integer.parseInt(in.readLine());

System.out.println("Enter second no.:");

y[0]=Integer.parseInt(in.readLine());

if(x[0] > y[0])

System.out.println(x[0]+" is greater than "+y[0]);

else

System.out.println(y[0]+" is greater than "+x[0]);

}

}

Page 3: Adv. Java Lab Manual

3

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 4: Adv. Java Lab Manual

4

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 2

Aim: - Write a Program To Find Minimum of two numbers.

Page 5: Adv. Java Lab Manual

5

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.io.*;

import java.util.*;

import java.math.*;

public class Minof2{

public static void main(String args[])throws IOException{

int[] x=new int[1];

int[] y=new int[1];

BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter first no.:");

x[0]=Integer.parseInt(in.readLine());

System.out.println("Enter second no.:");

y[0]=Integer.parseInt(in.readLine());

if(x[0] < y[0])

System.out.println(x[0]+" is smaller than "+y[0]);

else

System.out.println(y[0]+" is smaller than "+x[0]);

}

}

Page 6: Adv. Java Lab Manual

6

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 7: Adv. Java Lab Manual

7

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 3

Aim: - Write a program that will read a float type value

From the keyboard and print the following output.

->Small Integer not less than the number.

->Given Number.

->Largest Integer not greater than the number.

Page 8: Adv. Java Lab Manual

8

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

class ValueFormat

{

public static void main(String args[])

{

double i = 34.32; //given number

System.out.println("Small Integer not greater than the number : "+Math.ceil(i));

System.out.println("Given Number : "+i);

System.out.println("Largest Integer not greater than the number : "+Math.floor(i));

}

}

Page 9: Adv. Java Lab Manual

9

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 10: Adv. Java Lab Manual

10

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 4

Aim: - Write a program to generate five Random numbers

between 1 to 100, and it should not follow with

decimal point.

Page 11: Adv. Java Lab Manual

11

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

class RandomDemo{

public static void main(String args[]){

for(int i=1;i<=5;i++){

System.out.println((int)(Math.random()*100));

}

}

}

Page 12: Adv. Java Lab Manual

12

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 13: Adv. Java Lab Manual

13

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 5

Aim: - Write a program to display a greet message according

to Marks obtained by student.

Page 14: Adv. Java Lab Manual

14

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.io.*;

import java.util.*;

import java.math.*;

class SwitchDemo{

public static void main(String args[]) throws IOException{

int[] x=new int[1];

BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter Number.:");

x[0]=Integer.parseInt(in.readLine());

switch(x[0]/10){

case 10:

case 9:

case 8:

System.out.println("Excellent");

break;

case 7:

System.out.println("Very Good");

break;

case 6:

System.out.println("Good");

break;

case 5:

System.out.println("Work Hard");

Page 15: Adv. Java Lab Manual

15

ROHIT BHATIA Advance Java.

08-CSE-133

break;

case 4:

System.out.println("Poor");

break;

case 3:

case 2:

case 1:

case 0:

System.out.println("Very Poor");

break;

default:

System.out.println("Invalid value Entered");

}

}

}

Page 16: Adv. Java Lab Manual

16

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 17: Adv. Java Lab Manual

17

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 6

Aim: - Write a program to find Sum & Product of a

given Digit.

Page 18: Adv. Java Lab Manual

18

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

class Sum_Product_ofDigit{

public static void main(String args[]){

int num = Integer.parseInt(args[0]); //taking value as command line

argument.

int temp = num,result=0;

//Logic for sum of digit

while(temp>0){

result = result + temp;

temp--;

}

System.out.println("Sum of Digit for "+num+" is : "+result);

//Logic for product of digit

temp = num;

result = 1;

while(temp > 0){

result = result * temp;

temp--; }

System.out.println("Product of Digit for "+num+" is : "+result);

}

}

Page 19: Adv. Java Lab Manual

19

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 20: Adv. Java Lab Manual

20

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 7

Aim: - Write a program to find Factorial of Given number.

Page 21: Adv. Java Lab Manual

21

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

class Factorial{

public static void main(String args[]){

int num = Integer.parseInt(args[0]); //take argument as command line

int result = 1;

while(num>0){

result = result * num;

num--;

}

System.out.println("Factorial of Given no. is : "+result);

}

}

Page 22: Adv. Java Lab Manual

22

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 23: Adv. Java Lab Manual

23

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 8

Aim: - Write a program to reverse the given number.

Page 24: Adv. Java Lab Manual

24

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

class Reverse{

public static void main(String args[]){

int num = Integer.parseInt(args[0]); //take argument as command line

int remainder, result=0;

while(num>0){

remainder = num%10;

result = result * 10 + remainder;

num = num/10;

}

System.out.println("Reverse number is : "+result);

}

}

Page 25: Adv. Java Lab Manual

25

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 26: Adv. Java Lab Manual

26

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 9

Aim: - Write a program to show the use of Date functionality.

Page 27: Adv. Java Lab Manual

27

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.text.DateFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

public class DateUtility {

/* Add Day/Month/Year to a Date

add() is used to add values to a Calendar object.

You specify which Calendar field is to be affected by the operation

(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).

*/

public static void addToDate(){

System.out.println("In the ADD Operation");

// String DATE_FORMAT = "yyyy-MM-dd";

String DATE_FORMAT = "dd-MM-yyyy"; //Refer Java DOCS for

formats

java.text.SimpleDateFormat sdf = new

java.text.SimpleDateFormat(DATE_FORMAT);

Calendar c1 = Calendar.getInstance();

Date d1 = new Date();

System.out.println("Todays date in Calendar Format : "+c1);

System.out.println("c1.getTime() : "+c1.getTime());

System.out.println("c1.get(Calendar.YEAR): " + c1.get(Calendar.YEAR));

System.out.println("Todays date in Date Format : "+d1);

c1.set(1999,0 ,20); //(year,month,date)

System.out.println("c1.set(1999,0 ,20) : "+c1.getTime());

c1.add(Calendar.DATE,40);

System.out.println("Date + 20 days is : " + sdf.format(c1.getTime()));

System.out.println();

System.out.println();

}

/*Substract Day/Month/Year to a Date

roll() is used to substract values to a Calendar object.

You specify which Calendar field is to be affected by the operation

(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).

Note: To substract, simply use a negative argument.

roll() does the same thing except you specify if you want to roll up (add 1)

or roll down (substract 1) to the specified Calendar field. The operation only

affects the specified field while add() adjusts other Calendar fields.

See the following example, roll() makes january rolls to december in the same

year while add() substract the YEAR field for the correct result

*/

Page 28: Adv. Java Lab Manual

28

ROHIT BHATIA Advance Java.

08-CSE-133

public static void subToDate(){

System.out.println("In the SUB Operation");

String DATE_FORMAT = "dd-MM-yyyy";

java.text.SimpleDateFormat sdf = new

java.text.SimpleDateFormat(DATE_FORMAT);

Calendar c1 = Calendar.getInstance();

c1.set(1999, 0 , 20);

System.out.println("Date is : " + sdf.format(c1.getTime()));

// roll down, substract 1 month

c1.roll(Calendar.MONTH, false);

System.out.println("Date roll down 1 month : " + sdf.format(c1.getTime()));

c1.set(1999, 0 , 20);

System.out.println("Date is : " + sdf.format(c1.getTime()));

c1.add(Calendar.MONTH, -1);

// substract 1 month

System.out.println("Date minus 1 month : " + sdf.format(c1.getTime()));

System.out.println();

System.out.println();

}

public static void daysBetween2Dates(){

Calendar c1 = Calendar.getInstance(); //new GregorianCalendar();

Calendar c2 = Calendar.getInstance(); //new GregorianCalendar();

c1.set(1999, 0 , 20);

c2.set(1999, 0 , 22);

System.out.println("Days Between "+c1.getTime()+"\t"+ c2.getTime()+" is");

System.out.println((c2.getTime().getTime() -

c1.getTime().getTime())/(24*3600*1000));

System.out.println();

System.out.println();

}

public static void daysInMonth() {

Calendar c1 = Calendar.getInstance(); //new GregorianCalendar();

c1.set(1999, 6 , 20);

int year = c1.get(Calendar.YEAR);

int month = c1.get(Calendar.MONTH);

// int days = c1.get(Calendar.DATE);

int [] daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31};

daysInMonths[1] += DateUtility.isLeapYear(year) ? 1 : 0;

System.out.println("Days in "+month+"th month for year "+year+" is "+

daysInMonths[c1.get(Calendar.MONTH)]);

System.out.println();

System.out.println();

}

Page 29: Adv. Java Lab Manual

29

ROHIT BHATIA Advance Java.

08-CSE-133

public static void getDayofTheDate() {

Date d1 = new Date();

String day = null;

DateFormat f = new SimpleDateFormat("EEEE");

try {

day = f.format(d1);

}

catch(Exception e) {

e.printStackTrace();

}

System.out.println("The dat for "+d1+" is "+day);

System.out.println();

System.out.println();

}

public static void validateAGivenDate() {

String dt = "20011223";

String invalidDt = "20031315";

String dateformat = "yyyyMMdd";

Date dt1=null , dt2=null;

try {

SimpleDateFormat sdf = new SimpleDateFormat(dateformat);

sdf.setLenient(false);

dt1 = sdf.parse(dt);

dt2 = sdf.parse(invalidDt);

System.out.println("Date is ok = " + dt1 + "(" + dt + ")");

}

catch (ParseException e) {

System.out.println(e.getMessage());

}

catch (IllegalArgumentException e) {

System.out.println("Invalid date");

}

System.out.println();

System.out.println();

}

public static void compare2Dates(){

SimpleDateFormat fm = new SimpleDateFormat("dd-MM-yyyy");

Calendar c1 = Calendar.getInstance();

Calendar c2 = Calendar.getInstance();

c1.set(2000, 02, 15);

c2.set(2001, 02, 15);

System.out.print(fm.format(c1.getTime())+" is ");

if(c1.before(c2)){

System.out.println("less than "+c2.getTime());

}else if(c1.after(c2)){

Page 30: Adv. Java Lab Manual

30

ROHIT BHATIA Advance Java.

08-CSE-133

System.out.println("greater than "+c2.getTime());

}else if(c1.equals(c2)){

System.out.println("is equal to "+fm.format(c2.getTime()));

}

System.out.println();

System.out.println();

}

public static boolean isLeapYear(int year){

if((year%100 != 0) || (year%400 == 0)){

return true;

}

return false;

}

public static void main(String args[]){

addToDate();

subToDate();

daysBetween2Dates(); //The "right" way would be to compute the julian

day number of both dates and then do the substraction.

daysInMonth();

validateAGivenDate();

compare2Dates();

getDayofTheDate();

}

}

Page 31: Adv. Java Lab Manual

31

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 32: Adv. Java Lab Manual

32

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 10

Aim: - Write a program to show use of JFrame program

in Swing.

Page 33: Adv. Java Lab Manual

33

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class JFrameDemo {

public static void main(String s[]) {

JFrame frame = new JFrame("JFrame Source Demo");

// Add a window listner for close button

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

// This is an empty content area in the frame

JLabel jlbempty = new JLabel("");

jlbempty.setPreferredSize(new Dimension(175, 100));

frame.getContentPane().add(jlbempty, BorderLayout.CENTER);

frame.pack();

frame.setVisible(true);

}

}

Page 34: Adv. Java Lab Manual

34

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 35: Adv. Java Lab Manual

35

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 11

Aim: - Write a program to show use of JInternalFrame program

in Swing.

Page 36: Adv. Java Lab Manual

36

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import javax.swing.JInternalFrame;

import javax.swing.JDesktopPane;

import javax.swing.JMenu;

import javax.swing.JMenuItem;

import javax.swing.JMenuBar;

import javax.swing.JFrame;

import java.awt.event.*;

import java.awt.*;

public class JInternalFrameDemo extends JFrame {

JDesktopPane jdpDesktop;

static int openFrameCount = 0;

public JInternalFrameDemo() {

super("JInternalFrame Usage Demo");

// Make the main window positioned as 50 pixels from each edge of the

// screen.

int inset = 50;

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

setBounds(inset, inset, screenSize.width - inset * 2,

screenSize.height - inset * 2);

// Add a Window Exit Listener

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

// Create and Set up the GUI.

jdpDesktop = new JDesktopPane();

// A specialized layered pane to be used with JInternalFrames

createFrame(); // Create first window

setContentPane(jdpDesktop);

setJMenuBar(createMenuBar());

// Make dragging faster by setting drag mode to Outline

Page 37: Adv. Java Lab Manual

37

ROHIT BHATIA Advance Java.

08-CSE-133

jdpDesktop.putClientProperty("JDesktopPane.dragMode", "outline");

}

protected JMenuBar createMenuBar() {

JMenuBar menuBar = new JMenuBar();

JMenu menu = new JMenu("Frame");

menu.setMnemonic(KeyEvent.VK_N);

JMenuItem menuItem = new JMenuItem("New IFrame");

menuItem.setMnemonic(KeyEvent.VK_N);

menuItem.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

createFrame();

}

});

menu.add(menuItem);

menuBar.add(menu);

return menuBar;

}

protected void createFrame() {

MyInternalFrame frame = new MyInternalFrame();

frame.setVisible(true);

// Every JInternalFrame must be added to content pane using

JDesktopPane

jdpDesktop.add(frame);

try {

frame.setSelected(true);

} catch (java.beans.PropertyVetoException e) {

}

}

public static void main(String[] args) {

JInternalFrameDemo frame = new JInternalFrameDemo();

frame.setVisible(true);

}

class MyInternalFrame extends JInternalFrame {

static final int xPosition = 30, yPosition = 30;

public MyInternalFrame() {

Page 38: Adv. Java Lab Manual

38

ROHIT BHATIA Advance Java.

08-CSE-133

super("IFrame #" + (++openFrameCount), true, // resizable

true, // closable

true, // maximizable

true);// iconifiable

setSize(300, 300);

// Set the window's location.

setLocation(xPosition * openFrameCount, yPosition

* openFrameCount);

}

}

}

Page 39: Adv. Java Lab Manual

39

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 40: Adv. Java Lab Manual

40

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 12

Aim: - Write a program to show use of JWindow program

in Swing.

Page 41: Adv. Java Lab Manual

41

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class JWindowDemo extends JWindow {

private int X = 0;

private int Y = 0;

public JWindowDemo() {

setBounds(60, 60, 100, 100);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0); // An Exit Listener

}

});

// Print (X,Y) coordinates on Mouse Click

addMouseListener(new MouseAdapter() {

public void mousePressed(MouseEvent e) {

X = e.getX();

Y = e.getY();

System.out.println("The (X,Y) coordinate of window is ("+ X + "," + Y + ")");

}

});

addMouseMotionListener(new MouseMotionAdapter() {

public void mouseDragged(MouseEvent e) {

setLocation(getLocation().x + (e.getX() - X),

getLocation().y + (e.getY() - Y));

}

});

setVisible(true);

}

public static void main(String[] args) {

new JWindowDemo();

}

}

Page 42: Adv. Java Lab Manual

42

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 43: Adv. Java Lab Manual

43

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 13

Aim: - Write a program to show use of JTextField program

in Swing.

Page 44: Adv. Java Lab Manual

44

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class JTextFieldDemo extends JFrame {

//Class Declarations

JTextField jtfText1, jtfUneditableText;

String disp = "";

TextHandler handler = null;

//Constructor

public JTextFieldDemo() {

super("TextField Test Demo");

Container container = getContentPane();

container.setLayout(new FlowLayout());

jtfText1 = new JTextField(10);

jtfUneditableText = new JTextField("Uneditable text field", 20);

jtfUneditableText.setEditable(false);

container.add(jtfText1);

container.add(jtfUneditableText);

handler = new TextHandler();

jtfText1.addActionListener(handler);

jtfUneditableText.addActionListener(handler);

Page 45: Adv. Java Lab Manual

45

ROHIT BHATIA Advance Java.

08-CSE-133

setSize(325, 100);

setVisible(true);

}

//Inner Class TextHandler

private class TextHandler implements ActionListener {

public void actionPerformed(ActionEvent e) {

if (e.getSource() == jtfText1) {

disp = "text1 : " + e.getActionCommand();

} else if (e.getSource() == jtfUneditableText) {

disp = "text3 : " + e.getActionCommand();

}

JOptionPane.showMessageDialog(null, disp);

}

}

//Main Program that starts Execution

public static void main(String args[]) {

JTextFieldDemo test = new JTextFieldDemo();

test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}

Page 46: Adv. Java Lab Manual

46

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 47: Adv. Java Lab Manual

47

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 14

Aim: - Write a program to show use of JButton program

in Swing.

Page 48: Adv. Java Lab Manual

48

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

import java.net.URL;

import javax.swing.AbstractButton;

import javax.swing.ImageIcon;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class JButtonDemo extends JPanel implements ActionListener {

protected static JButton jbnLeft, jbnMiddle, jbnRight;

public JButtonDemo() {

// Create Icons that can be used with the jButtons

ImageIcon leftButtonIcon = createImageIcon("rightarrow.JPG");

ImageIcon middleButtonIcon = createImageIcon("java-swing-

tutorial.JPG");

ImageIcon rightButtonIcon = createImageIcon("leftarrow.JPG");

jbnLeft = new JButton("Disable centre button", leftButtonIcon);

jbnLeft.setVerticalTextPosition(AbstractButton.CENTER);

jbnLeft.setHorizontalTextPosition(AbstractButton.LEADING);

jbnLeft.setMnemonic(KeyEvent.VK_D);

// Alt-D clicks the button

jbnLeft.setActionCommand("disable");

jbnLeft.setToolTipText("disable the Centre button."); // Adding Tool

// tips

jbnMiddle = new JButton("Centre button", middleButtonIcon);

jbnMiddle.setVerticalTextPosition(AbstractButton.BOTTOM);

jbnMiddle.setHorizontalTextPosition(AbstractButton.CENTER);

jbnMiddle.setMnemonic(KeyEvent.VK_M);

// Alt-M clicks the button

jbnMiddle.setToolTipText("Centre button");

jbnRight = new JButton("Enable centre button", rightButtonIcon);

// Use the default text position of CENTER, TRAILING (RIGHT).

jbnRight.setMnemonic(KeyEvent.VK_E);

// Alt-E clicks the button

Page 49: Adv. Java Lab Manual

49

ROHIT BHATIA Advance Java.

08-CSE-133

jbnRight.setActionCommand("enable");

jbnRight.setEnabled(false);

// Disable the Button at creation time

// Listen for actions on Left and Roght Buttons

jbnLeft.addActionListener(this);

jbnRight.addActionListener(this);

jbnRight.setToolTipText("Enable the Centre button.");

// Add Components to the frame, using the default FlowLayout.

add(jbnLeft);

add(jbnMiddle);

add(jbnRight);

}

public void actionPerformed(ActionEvent e) {

if ("disable".equals(e.getActionCommand())) {

jbnMiddle.setEnabled(false);

jbnLeft.setEnabled(false);

jbnRight.setEnabled(true);

} else {

jbnMiddle.setEnabled(true);

jbnLeft.setEnabled(true);

jbnRight.setEnabled(false);

}

}

// Returns an ImageIcon, or null if the path was invalid.

protected static ImageIcon createImageIcon(String path) {

URL imgURL = JButtonDemo.class.getResource(path);

if (imgURL != null) {

return new ImageIcon(imgURL);

} else {

System.err.println("Couldn't find image in system: " + path);

return null;

}

}

// Create the GUI and show it.

private static void createGUI() {

JFrame.setDefaultLookAndFeelDecorated(true);

// Create and set up the frame.

Page 50: Adv. Java Lab Manual

50

ROHIT BHATIA Advance Java.

08-CSE-133

JFrame frame = new JFrame("jButton usage demo");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create and set up the content pane.

JButtonDemo buttonContentPane = new JButtonDemo();

buttonContentPane.setOpaque(true); // content panes must be opaque

frame.getRootPane().setDefaultButton(jbnLeft);

frame.setContentPane(buttonContentPane);

// Display the window.

frame.pack();

frame.setVisible(true);

}

public static void main(String[] args) {

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {

createGUI();

}

});

}

}

Page 51: Adv. Java Lab Manual

51

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 52: Adv. Java Lab Manual

52

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 15

Aim: - Write a program to show use of JCheckBox program

in Swing.

Page 53: Adv. Java Lab Manual

53

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class JCheckBoxDemo extends JPanel {

//Four accessory choices provide for 16 different combinations

JCheckBox jcbChin;

JCheckBox jcbGlasses;

JCheckBox jcbHair;

JCheckBox jcbTeeth;

/* The image for each combination is contained in a

separate image file whose name indicates the accessories.

The filenames are "geek-XXXX.gif" where XXXX can be one

* of the following 16 choices.

*/

StringBuffer choices;

JLabel jlbPicture;

CheckBoxListener myListener = null;

public JCheckBoxDemo() {

// Add an item listener for each of the check boxes.

// This is the listener class which contains business logic

myListener = new CheckBoxListener();

// Create check boxes with default selection true

jcbChin = new JCheckBox("Chin");

jcbChin.setMnemonic(KeyEvent.VK_C);

//Alt+C Checks/Unchecks the check Box

jcbChin.setSelected(true);

jcbChin.addItemListener(myListener);

jcbGlasses = new JCheckBox("Glasses");

jcbGlasses.setMnemonic(KeyEvent.VK_G);

//Alt+G Checks/Unchecks the check Box

jcbGlasses.setSelected(true);

Page 54: Adv. Java Lab Manual

54

ROHIT BHATIA Advance Java.

08-CSE-133

jcbGlasses.addItemListener(myListener);

jcbHair = new JCheckBox("Hair");

jcbHair.setMnemonic(KeyEvent.VK_H);

//Alt+H Checks/Unchecks the check Box

jcbHair.setSelected(true);

jcbHair.addItemListener(myListener);

jcbTeeth = new JCheckBox("Teeth");

jcbTeeth.setMnemonic(KeyEvent.VK_T);

//Alt+T Checks/Unchecks the check Box

jcbTeeth.setSelected(true);

jcbTeeth.addItemListener(myListener);

// Indicates what's on the geek.

choices = new StringBuffer("cght");//Default Image has all the parts.

// Set up the picture label

jlbPicture = new JLabel(new ImageIcon("geek-" +

choices.toString().trim() + ".gif"));

jlbPicture.setToolTipText(choices.toString().trim());

// Put the check boxes in a column in a panel

JPanel jplCheckBox = new JPanel();

jplCheckBox.setLayout(new GridLayout(0, 1)); //0 rows, 1 Column

jplCheckBox.add(jcbChin);

jplCheckBox.add(jcbGlasses);

jplCheckBox.add(jcbHair);

jplCheckBox.add(jcbTeeth);

setLayout(new BorderLayout());

add(jplCheckBox, BorderLayout.WEST);

add(jlbPicture, BorderLayout.CENTER);

setBorder(BorderFactory.createEmptyBorder(20,20,20,20));

}

//Listens to the check boxes events

Page 55: Adv. Java Lab Manual

55

ROHIT BHATIA Advance Java.

08-CSE-133

class CheckBoxListener implements ItemListener {

public void itemStateChanged(ItemEvent e) {

int index = 0;

char c = '-';

Object source = e.getSource();

if (source == jcbChin) {

index = 0;

c = 'c';

} else if (source == jcbGlasses) {

index = 1;

c = 'g';

} else if (source == jcbHair) {

index = 2;

c = 'h';

} else if (source == jcbTeeth) {

index = 3;

c = 't';

}

if (e.getStateChange() == ItemEvent.DESELECTED)

c = '-';

choices.setCharAt(index, c);

jlbPicture.setIcon(new ImageIcon("geek-"

+ choices.toString().trim() + ".gif"));

jlbPicture.setToolTipText(choices.toString());

}

}

public static void main(String s[]) {

JFrame frame = new JFrame("JCheckBox Usage Demo");

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

frame.setContentPane(new JCheckBoxDemo());

frame.pack();

frame.setVisible(true); }}

Page 56: Adv. Java Lab Manual

56

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 57: Adv. Java Lab Manual

57

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 16

Aim: - Write a program to show use of JComboBox program

in Swing.

Page 58: Adv. Java Lab Manual

58

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class JComboBoxDemo extends JPanel {

JLabel jlbPicture;

public JComboBoxDemo() {

String[] comboTypes = { "Numbers", "Alphabets", "Symbols" };

// Create the combo box, and set 2nd item as Default

JComboBox comboTypesList = new JComboBox(comboTypes);

comboTypesList.setSelectedIndex(2);

comboTypesList.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

JComboBox jcmbType = (JComboBox) e.getSource();

String cmbType = (String) jcmbType.getSelectedItem();

jlbPicture.setIcon(new ImageIcon(""

+ cmbType.trim().toLowerCase() + ".jpg"));

}

});

// Set up the picture

jlbPicture = new JLabel(new ImageIcon(""

+ comboTypes[comboTypesList.getSelectedIndex()] +

".jpg"));

jlbPicture.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));

Page 59: Adv. Java Lab Manual

59

ROHIT BHATIA Advance Java.

08-CSE-133

jlbPicture.setPreferredSize(new Dimension(177, 122 + 10));

// Layout the demo

setLayout(new BorderLayout());

add(comboTypesList, BorderLayout.NORTH);

add(jlbPicture, BorderLayout.SOUTH);

setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

}

public static void main(String s[]) {

JFrame frame = new JFrame("JComboBox Usage Demo");

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

frame.setContentPane(new JComboBoxDemo());

frame.pack();

frame.setVisible(true);

}

}

Page 60: Adv. Java Lab Manual

60

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 61: Adv. Java Lab Manual

61

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 17

Aim: - Write a program to show use of JList program in Swing.

Page 62: Adv. Java Lab Manual

62

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import javax.swing.*;

import javax.swing.event.ListSelectionEvent;

import javax.swing.event.ListSelectionListener;

import java.awt.*;

import java.awt.event.*;

public class JListDemo extends JFrame {

JList list;

String[] listColorNames = { "black", "blue", "green", "yellow",

"white" };

Color[] listColorValues = { Color.BLACK, Color.BLUE, Color.GREEN,

Color.YELLOW, Color.WHITE };

Container contentpane;

public JListDemo() {

super("List Source Demo");

contentpane = getContentPane();

contentpane.setLayout(new FlowLayout());

list = new JList(listColorNames);

list.setSelectedIndex(0);

list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

contentpane.add(new JScrollPane(list));

list.addListSelectionListener(new ListSelectionListener() {

Page 63: Adv. Java Lab Manual

63

ROHIT BHATIA Advance Java.

08-CSE-133

public void valueChanged(ListSelectionEvent e) {

contentpane.setBackground(listColorValues[list

.getSelectedIndex()]);

}

});

setSize(200, 200);

setVisible(true);

}

public static void main(String[] args) {

JListDemo test = new JListDemo();

test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}

Page 64: Adv. Java Lab Manual

64

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 65: Adv. Java Lab Manual

65

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 18

Aim: - Write a program to show use of JMenu program in

Swing.

Page 66: Adv. Java Lab Manual

66

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.awt.*;

import java.awt.event.*;

import javax.swing.JMenu;

import javax.swing.JMenuItem;

import javax.swing.JCheckBoxMenuItem;

import javax.swing.JRadioButtonMenuItem;

import javax.swing.ButtonGroup;

import javax.swing.JMenuBar;

import javax.swing.KeyStroke;

import javax.swing.ImageIcon;

import javax.swing.JPanel;

import javax.swing.JTextArea;

import javax.swing.JScrollPane;

import javax.swing.JFrame;

//Used Action Listner for JMenuItem & JRadioButtonMenuItem

//Used Item Listner for JCheckBoxMenuItem

public class JMenuDemo implements ActionListener, ItemListener {

JTextArea jtAreaOutput;

JScrollPane jspPane;

public JMenuBar createJMenuBar() {

JMenuBar mainMenuBar;

JMenu menu1, menu2, submenu;

JMenuItem plainTextMenuItem, textIconMenuItem, iconMenuItem,

subMenuItem;

JRadioButtonMenuItem rbMenuItem;

JCheckBoxMenuItem cbMenuItem;

ImageIcon icon = createImageIcon("jmenu.jpg");

mainMenuBar = new JMenuBar();

menu1 = new JMenu("Menu 1");

menu1.setMnemonic(KeyEvent.VK_M);

mainMenuBar.add(menu1);

// Creating the MenuItems

plainTextMenuItem = new JMenuItem("Menu item with Plain Text",

KeyEvent.VK_T);

// can be done either way for assigning shortcuts

Page 67: Adv. Java Lab Manual

67

ROHIT BHATIA Advance Java.

08-CSE-133

// menuItem.setMnemonic(KeyEvent.VK_T);

// Accelerators, offer keyboard shortcuts to bypass navigating the menu

// hierarchy.

plainTextMenuItem.setAccelerator(KeyStroke.getKeyStroke(

KeyEvent.VK_1, ActionEvent.ALT_MASK));

plainTextMenuItem.addActionListener(this);

menu1.add(plainTextMenuItem);

textIconMenuItem = new JMenuItem("Menu Item with Text & Image",

icon);

textIconMenuItem.setMnemonic(KeyEvent.VK_B);

textIconMenuItem.addActionListener(this);

menu1.add(textIconMenuItem);

// Menu Item with just an Image

iconMenuItem = new JMenuItem(icon);

iconMenuItem.setMnemonic(KeyEvent.VK_D);

iconMenuItem.addActionListener(this);

menu1.add(iconMenuItem);

menu1.addSeparator();

// Radio Button Menu items follow a seperator

ButtonGroup itemGroup = new ButtonGroup();

rbMenuItem = new JRadioButtonMenuItem(

"Menu Item with Radio Button");

rbMenuItem.setSelected(true);

rbMenuItem.setMnemonic(KeyEvent.VK_R);

itemGroup.add(rbMenuItem);

rbMenuItem.addActionListener(this);

menu1.add(rbMenuItem);

rbMenuItem = new JRadioButtonMenuItem(

"Menu Item 2 with Radio Button");

itemGroup.add(rbMenuItem);

rbMenuItem.addActionListener(this);

menu1.add(rbMenuItem);

menu1.addSeparator();

// Radio Button Menu items follow a seperator

cbMenuItem = new JCheckBoxMenuItem("Menu Item with check

box");

cbMenuItem.setMnemonic(KeyEvent.VK_C);

Page 68: Adv. Java Lab Manual

68

ROHIT BHATIA Advance Java.

08-CSE-133

cbMenuItem.addItemListener(this);

menu1.add(cbMenuItem);

cbMenuItem = new JCheckBoxMenuItem("Menu Item 2 with check

box");

cbMenuItem.addItemListener(this);

menu1.add(cbMenuItem);

menu1.addSeparator();

// Sub Menu follows a seperator

submenu = new JMenu("Sub Menu");

submenu.setMnemonic(KeyEvent.VK_S);

subMenuItem = new JMenuItem("Sub MenuItem 1");

subMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2,

ActionEvent.CTRL_MASK));

subMenuItem.addActionListener(this);

submenu.add(subMenuItem);

subMenuItem = new JMenuItem("Sub MenuItem 2");

submenu.add(subMenuItem);

subMenuItem.addActionListener(this);

menu1.add(submenu);

// Build second menu in the menu bar.

menu2 = new JMenu("Menu 2");

menu2.setMnemonic(KeyEvent.VK_N);

mainMenuBar.add(menu2);

return mainMenuBar;

}

public Container createContentPane() {

// Create the content-pane-to-be.

JPanel jplContentPane = new JPanel(new BorderLayout());

jplContentPane.setLayout(new BorderLayout());// Can do it either way

// to set layout

jplContentPane.setOpaque(true);

// Create a scrolled text area.

jtAreaOutput = new JTextArea(5, 30);

jtAreaOutput.setEditable(false);

jspPane = new JScrollPane(jtAreaOutput);

// Add the text area to the content pane.

jplContentPane.add(jspPane, BorderLayout.CENTER);

Page 69: Adv. Java Lab Manual

69

ROHIT BHATIA Advance Java.

08-CSE-133

return jplContentPane;

}

/** Returns an ImageIcon, or null if the path was invalid. */

protected static ImageIcon createImageIcon(String path) {

java.net.URL imgURL = JMenuDemo.class.getResource(path);

if (imgURL != null) {

return new ImageIcon(imgURL);

} else {

System.err.println("Couldn't find image file: " + path);

return null;

}

}

private static void createGUI() {

JFrame.setDefaultLookAndFeelDecorated(true);

// Create and set up the window.

JFrame frame = new JFrame("JMenu Usage Demo");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JMenuDemo app = new JMenuDemo();

frame.setJMenuBar(app.createJMenuBar());

frame.setContentPane(app.createContentPane());

frame.setSize(500, 300);

frame.setVisible(true);

}

public void actionPerformed(ActionEvent e) {

JMenuItem source = (JMenuItem) (e.getSource());

String s = "Menu Item source: " + source.getText()

+ " (an instance of " + getClassName(source) + ")";

jtAreaOutput.append(s + "\n");

jtAreaOutput.setCaretPosition(jtAreaOutput.getDocument()

.getLength());

}

public void itemStateChanged(ItemEvent e) {

JMenuItem source = (JMenuItem) (e.getSource());

String s = "Menu Item source: "

+ source.getText()

+ " (an instance of "

+ getClassName(source)

Page 70: Adv. Java Lab Manual

70

ROHIT BHATIA Advance Java.

08-CSE-133

+ ")"

+ "\n"

+ " State of check Box: "

+ ((e.getStateChange() == ItemEvent.SELECTED) ?

"selected"

: "unselected");

jtAreaOutput.append(s + "\n");

jtAreaOutput.setCaretPosition(jtAreaOutput.getDocument()

.getLength());

}

// Returns the class name, no package info

protected String getClassName(Object o) {

String classString = o.getClass().getName();

int dotIndex = classString.lastIndexOf(".");

return classString.substring(dotIndex + 1); // Returns only Class name

}

public static void main(String[] args) {

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {

createGUI();

}

});

}

}

Page 71: Adv. Java Lab Manual

71

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 72: Adv. Java Lab Manual

72

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 19

Aim: - Write a program to show use of MYSQL program.

Page 73: Adv. Java Lab Manual

73

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.sql.*;

public class MysqlConnect{

public static void main(String[] args) {

System.out.println("MySQL Connect Example.");

Connection conn = null;

String url = "jdbc:mysql://localhost:3306/";

String dbName = "jdbctutorial";

String driver = "com.mysql.jdbc.Driver";

String userName = "root";

String password = "root";

try {

Class.forName(driver).newInstance();

conn = DriverManager.getConnection(url+dbName,userName,password);

System.out.println("Connected to the database");

conn.close();

System.out.println("Disconnected from database");

} catch (Exception e) {

e.printStackTrace();

}

}

}

Page 74: Adv. Java Lab Manual

74

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 75: Adv. Java Lab Manual

75

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 20

Aim: - Tutorial On Net Beans.

Page 76: Adv. Java Lab Manual

76

ROHIT BHATIA Advance Java.

08-CSE-133

Setting Up the Project

To create an IDE project:

1. Start NetBeans IDE.

2. In the IDE, choose File > New Project (Ctrl-Shift-N), as shown in the figure below.

3. In the New Project wizard, expand the Java category and select Java Application as shown

in the figure below. Then click Next.

4. In the Name and Location page of the wizard, do the following (as shown in the figure

below):

o In the Project Name field, type HelloWorldApp.

o Leave the Use Dedicated Folder for Storing Libraries checkbox unselected.

o In the Create Main Class field, type helloworldapp.HelloWorldApp.

o Leave the Set as Main Project checkbox selected.

Page 77: Adv. Java Lab Manual

77

ROHIT BHATIA Advance Java.

08-CSE-133

5. Click Finish.

The project is created and opened in the IDE. You should see the following components:

The Projects window, which contains a tree view of the components of the project,

including source files, libraries that your code depends on, and so on.

The Source Editor window with a file called HelloWorldApp open.

The Navigator window, which you can use to quickly navigate between elements within the

selected class.

The Tasks window, which lists compilation errors as well other tasks that are marked with

keywords such as XXX and TODO.

Page 78: Adv. Java Lab Manual

78

ROHIT BHATIA Advance Java.

08-CSE-133

Adding Code to the Generated Source File

Because you have left the Create Main Class checkbox selected in the New Project wizard, the IDE

has created a skeleton main class for you. You can add the "Hello World!" message to the skeleton

code by replacing the line:

// TODO code application logic here

with the line: System.out.println("Hello World!");

Save the change by choosing File > Save.

The file should look something like the following code sample.

/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

package helloworldapp;

Page 79: Adv. Java Lab Manual

79

ROHIT BHATIA Advance Java.

08-CSE-133

/**

*

* @author <your name>

*/

public class HelloWorldApp {

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

System.out.println("Hello World!");

}

}

Compiling and Running the Program

Because of the IDE's Compile on Save feature, you do not have to manually compile your project in

order to run it in the IDE. When you save a Java source file, the IDE automatically compiles it.

The Compile on Save feature can be turned off in the Project Properties window. Right-click your

project, select Properties. In the Properties window, choose the Compiling tab. The Compile on

Save checkbox is right at the top. Note that in the Project Properties window you can configure

numerous settings for your project: project libraries, packaging, building, running, etc.

To run the program:

Choose Run > Run Main Project (F6).

If there are compilation errors, they are marked with red glyphs in the left and right margins of the

Source Editor. The glyphs in the left margin indicate errors for the corresponding lines. The glyphs

in the right margin show all of the areas of the file that have errors, including errors in lines that are

not visible. You can mouse over an error mark to get a description of the error. You can click a

glyph in the right margin to jump to the line with the error.

Building and Deploying the Application

Once you have written and test run your application, you can use the Clean and Build command to

build your application for deployment. When you use the Clean and Build command, the IDE runs

a build script that performs the following tasks:

Deletes any previously compiled files and other build outputs.

Recompiles the application and builds a JAR file containing the compiled files.

To build your application:

Choose Run > Clean and Build Main Project (Shift-F11)

Page 80: Adv. Java Lab Manual

80

ROHIT BHATIA Advance Java.

08-CSE-133

You can view the build outputs by opening the Files window and expanding the HelloWorldApp

node. The compiled bytecode file HelloWorldApp.class is within the

build/classes/helloworldapp subnode. A deployable JAR file that contains the

HelloWorldApp.class is within the dist node.

Page 81: Adv. Java Lab Manual

81

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 21

Aim: - Write a program to show use of NetBeans program.

Page 82: Adv. Java Lab Manual

82

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

package helloworldapp;

/**

*

* @author <your name>

*/

public class HelloWorldApp {

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

System.out.println("Hello World!");

}

}

Page 83: Adv. Java Lab Manual

83

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 84: Adv. Java Lab Manual

84

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 22

Aim: - Write a program to show use of JDBC.

Page 85: Adv. Java Lab Manual

85

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import javax.swing.JOptionPane;

import java.sql.*;

public class JdbcDemo

{

public static void main(String args[])

{

JOptionPane.showMessageDialog(null,"Welcome to JDBC Demo");

int choice = -1;

String userid="scott";

String password = "tiger";

do

{

choice = getChoice();

if (choice != 0)

{

getSelected(choice, userid, password);

}

}

while ( choice != 0);

System.exit(0);

}

public static int getChoice(){

String choice;

int ch;

choice = JOptionPane.showInputDialog(null,

"1. Create Coffees Table\n"+

"2. Insert Values into Coffees Table\n"+

"3. Create Suppliers Table\n"+

"4. Insert Values into Suppliers Table\n"+

"5. Update Table Example on Coffees Table\n"+

"6. A PreparedStatement Demo On Coffees Table\n"+

"7. A PreparedStatement Demo On Coffees Table using a FOR

Statement\n"+

"8. List of the coffees he buys from Acme, Inc [Supplier]\n"+

"9. Using Transactions Demo"+

Page 86: Adv. Java Lab Manual

86

ROHIT BHATIA Advance Java.

08-CSE-133

"10. Creating a Stored Procedue Demo\n"+

"11. Using Callable Statement to call a Stored Procedure\n"+

"12. Batch Update Demo\n"+

"0. Exit\n\n"+

"Enter your choice");

ch = Integer.parseInt(choice);

return ch;

}

public static void getSelected(int choice, String userid, String password)

{

if(choice==1)

{

createCoffees(userid, password);

}

else if(choice==2)

{

insertCoffees(userid, password);

}

else if(choice==3)

{

createSuppliers(userid, password);

}

else if(choice==4)

{

insertSuppliers(userid, password);

}

else if(choice==5)

{

updateCoffees(userid, password);

}

else if(choice==6)

{

prepare1Demo(userid, password);

}

else if(choice==7)

{

prepare2Demo(userid, password);

Page 87: Adv. Java Lab Manual

87

ROHIT BHATIA Advance Java.

08-CSE-133

}

else if(choice==8)

{

joinDemo(userid, password);

}

else if(choice==9)

{

transDemo(userid, password);

}

else if(choice==10)

{

createProcedure1(userid, password);

}

else if(choice==11)

{

callableDemo(userid, password);

}

else if(choice==12)

{

batchUpdateDemo(userid, password);

}

}

// Create Coffees Table

public static void createCoffees(String userid, String password)

{

String url = "jdbc:odbc:bob"; // String url =

"jdbc:mySubprotocol:myDataSource"; ?

//

jdbc:subprotocol:subname

Connection con;

String createString;

createString = "create table COFFEES " +

"(COF_NAME varchar(32), " +

"SUP_ID int, " +

"PRICE float, " +

"SALES int, " +

Page 88: Adv. Java Lab Manual

88

ROHIT BHATIA Advance Java.

08-CSE-133

"TOTAL int)";

Statement stmt;

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

//Class.forName("myDriver.ClassName"); ?

} catch(java.lang.ClassNotFoundException e) {

System.err.print("ClassNotFoundException: ");

System.err.println(e.getMessage());

}

try { con = DriverManager.getConnection(url, "userid", "password");

stmt = con.createStatement();

stmt.executeUpdate(createString);

stmt.close();

con.close();

} catch(SQLException ex) {

System.err.println("SQLException: " + ex.getMessage());

}

}

// Insert values into Coffees Table

public static void insertCoffees(String userid, String password)

{

String url = "jdbc:odbc:bob";

Connection con;

Statement stmt;

String query = "select COF_NAME, PRICE from COFFEES";

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {

System.err.print("ClassNotFoundException: ");

System.err.println(e.getMessage());

}

try {con = DriverManager.getConnection(url, "userid", "password");

stmt = con.createStatement();

stmt.executeUpdate("insert into COFFEES " +"values('Colombian', 00101,

7.99, 0, 0)");

Page 89: Adv. Java Lab Manual

89

ROHIT BHATIA Advance Java.

08-CSE-133

stmt.executeUpdate("insert into COFFEES " +"values('French_Roast',

00049, 8.99, 0, 0)");

stmt.executeUpdate("insert into COFFEES " + "values('Espresso', 00150,

9.99, 0, 0)");

stmt.executeUpdate("insert into COFFEES " +"values('Colombian_Decaf', 00101,

8.99, 0, 0)");

stmt.executeUpdate("insert into COFFEES " +"values('French_Roast_Decaf', 00049,

9.99, 0, 0)");

ResultSet rs = stmt.executeQuery(query);

System.out.println("Coffee Break Coffees and Prices:");

while (rs.next()) {

String s = rs.getString("COF_NAME"); // OR

rs.getString(1);

float f = rs.getFloat("PRICE"); // OR

rs.getFloat(3);

System.out.println(s + " " + f);

}

stmt.close();

con.close();

} catch(SQLException ex) {System.err.println("SQLException: " +

ex.getMessage());

}

}

// Create Suppliers Table

public static void createSuppliers(String userid, String password){

String url = "jdbc:odbc:bob";

Connection con;

String createString;

createString = "create table SUPPLIERS " +

"(SUP_ID int, " +

"SUP_NAME varchar(40), " +

"STREET varchar(40), " +

"CITY varchar(20), " +

"STATE char(2), ZIP char(5))";

Statement stmt;

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Page 90: Adv. Java Lab Manual

90

ROHIT BHATIA Advance Java.

08-CSE-133

} catch(java.lang.ClassNotFoundException e) {

System.err.print("ClassNotFoundException: ");

System.err.println(e.getMessage());

}

try {

con = DriverManager.getConnection(url,"userid",

"password");

stmt = con.createStatement();

stmt.executeUpdate(createString);

stmt.close();

con.close();

} catch(SQLException ex) { System.err.println("SQLException: " +

ex.getMessage()); } }

// Insert values into Coffees Table

public static void insertSuppliers(String userid, String password)

{

String url = "jdbc:odbc:bob";

Connection con;

Statement stmt;

String query = "select SUP_NAME, SUP_ID from SUPPLIERS";

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {

System.err.print("ClassNotFoundException: ");

System.err.println(e.getMessage());

}

try {

con = DriverManager.getConnection(url,"userid", "password");

stmt = con.createStatement();

stmt.executeUpdate("insert into SUPPLIERS " +

"values(49, 'Superior Coffee', '1 Party Place', " +

"'Mendocino', 'CA', '95460')");

stmt.executeUpdate("insert into SUPPLIERS " +

"values(101, 'Acme, Inc.', '99 Market Street', " +

"'Groundsville', 'CA', '95199')");

stmt.executeUpdate("insert into SUPPLIERS " +

"values(150, 'The High Ground', '100 Coffee Lane', " +

Page 91: Adv. Java Lab Manual

91

ROHIT BHATIA Advance Java.

08-CSE-133

"'Meadows', 'CA', '93966')");

ResultSet rs = stmt.executeQuery(query);

System.out.println("Suppliers and their ID Numbers:");

while (rs.next()) {

String s = rs.getString("SUP_NAME");

int n = rs.getInt("SUP_ID");

System.out.println(s + " " + n);

}

stmt.close();

con.close();

} catch(SQLException ex) {

System.err.println("SQLException: " + ex.getMessage());

}

}

// Update Coffees Table

public static void updateCoffees(String userid, String password)

{

String url = "jdbc:odbc:bob";

Connection con;

String updateString;

updateString = "UPDATE COFFEES " +

"SET SALES = 75 " +

"WHERE COF_NAME LIKE 'Colombian'";String query =

"SELECT COF_NAME, SALES FROM COFFEES " +"WHERE COF_NAME

LIKE 'Colombian'";

Statement stmt;

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {

System.err.print("ClassNotFoundException: ");

System.err.println(e.getMessage());

}

try {

con = DriverManager.getConnection(url,"userid",

"password");

stmt = con.createStatement();

stmt.executeUpdate(updateString);

Page 92: Adv. Java Lab Manual

92

ROHIT BHATIA Advance Java.

08-CSE-133

ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {

String s = rs.getString("COF_NAME"); //1

int n = rs.getInt("SALES"); //2

System.out.println(n + " pounds of " + s +

" sold this week.");

}

stmt.close();

con.close();

} catch(SQLException ex) {

System.err.println("SQLException: " + ex.getMessage());

} }

// Update Coffees Table using a prepared Statement

public static void prepare1Demo(String userid, String password)

{

String url = "jdbc:odbc:bob";

Connection con;

Statement stmt=null;

String query = "SELECT COF_NAME, SALES FROM

COFFEES ";

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {

System.err.print("ClassNotFoundException: ");

System.err.println(e.getMessage());

}

try {

con = DriverManager.getConnection(url,"userid", "password");

PreparedStatement updateSales = con.prepareStatement(

"UPDATE COFFEES SET SALES = ? WHERE COF_NAME

LIKE ? ");

updateSales.setInt(1, 75);

updateSales.setString(2, "Colombian");

updateSales.executeUpdate();

ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {

String s = rs.getString("COF_NAME"); //1

Page 93: Adv. Java Lab Manual

93

ROHIT BHATIA Advance Java.

08-CSE-133

int n = rs.getInt("SALES"); //2

System.out.println(s + " " + n);

}

stmt.close();

con.close();

} catch(SQLException ex) {

System.err.println("SQLException: " + ex.getMessage());

}

}

// Update Coffees Table using a prepared Statement

public static void prepare2Demo(String userid, String password)

{

String url = "jdbc:odbc:bob";

Connection con;

Statement stmt=null;

String query = "SELECT COF_NAME, SALES FROM COFFEES ";

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {

System.err.print("ClassNotFoundException: ");

System.err.println(e.getMessage());

}

try { con = DriverManager.getConnection(url,"userid", "password");

PreparedStatement updateSales;

String updateString = "update COFFEES " +

"set SALES = ? where COF_NAME like ?";

updateSales = con.prepareStatement(updateString);

int [] salesForWeek = {175, 150, 60, 155, 90};

String [] coffees = {"Colombian", "French_Roast", "Espresso",

"Colombian_Decaf", "French_Roast_Decaf"};

int len = coffees.length;

for(int i = 0; i < len; i++) {

updateSales.setInt(1, salesForWeek[i]);

updateSales.setString(2, coffees[i]);

updateSales.executeUpdate();

// int n= updateSales.executeUpdate() to find out how may rows have been updated

Page 94: Adv. Java Lab Manual

94

ROHIT BHATIA Advance Java.

08-CSE-133

}

ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {

String s = rs.getString("COF_NAME"); //1

int n = rs.getInt("SALES"); //2

System.out.println(s + " " + n);

}

stmt.close();

con.close();

} catch(SQLException ex) {

System.err.println("SQLException: " + ex.getMessage());}}

//Using join on 2 table to retrieve results

public static void joinDemo(String userid, String password)

{

String url = "jdbc:odbc:bob";

Connection con;

String query = "select SUPPLIERS.SUP_NAME,

COFFEES.COF_NAME " + "from COFFEES, SUPPLIERS " +

"where SUPPLIERS.SUP_NAME like 'Acme, Inc.' and " +

"SUPPLIERS.SUP_ID = COFFEES.SUP_ID";

Statement stmt;

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {

System.err.print("ClassNotFoundException: ");

System.err.println(e.getMessage());

}

try {

con = DriverManager.getConnection (url,"userid",

"password");

stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(query);

System.out.println("Supplier, Coffee:");

while (rs.next()) {

String supName = rs.getString(1);

String cofName = rs.getString(2);

System.out.println(" " + supName + ", " + cofName);

Page 95: Adv. Java Lab Manual

95

ROHIT BHATIA Advance Java.

08-CSE-133

}

stmt.close();

con.close();

} catch(SQLException ex) {

System.err.print("SQLException: ");

System.err.println(ex.getMessage());

}

}

// Using Transaction Autocommit Option

public static void transDemo(String userid, String password)

{

String url = "jdbc:odbc:bob";

Connection con=null;

Statement stmt;

PreparedStatement updateSales;

PreparedStatement updateTotal;

String updateString = "update COFFEES " +"set SALES = ?

where COF_NAME = ?";String updateStatement = "update COFFEES " +

"set TOTAL = TOTAL + ? where COF_NAME = ?";String query = "select

COF_NAME, SALES, TOTAL from COFFEES";

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {

System.err.print("ClassNotFoundException: ");

System.err.println(e.getMessage());

}

try {

con = DriverManager.getConnection(url,"userid", "password");

updateSales = con.prepareStatement(updateString);

updateTotal = con.prepareStatement(updateStatement);

int [] salesForWeek = {175, 150, 60, 155, 90};

String [] coffees = {"Colombian", "French_Roast","Espresso",

"Colombian_Decaf","French_Roast_Decaf"};

int len = coffees.length;

con.setAutoCommit(false);

for (int i = 0; i < len; i++) {

updateSales.setInt(1, salesForWeek[i]);

Page 96: Adv. Java Lab Manual

96

ROHIT BHATIA Advance Java.

08-CSE-133

updateSales.setString(2, coffees[i]);

updateSales.executeUpdate();

updateTotal.setInt(1, salesForWeek[i]);

updateTotal.setString(2, coffees[i]);

updateTotal.executeUpdate();

con.commit();

}

con.setAutoCommit(true);

updateSales.close();

updateTotal.close();

stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {

String c = rs.getString("COF_NAME");

int s = rs.getInt("SALES");

int t = rs.getInt("TOTAL");

System.out.println(c + " " + s + " " + t);

}

stmt.close();

con.close();

} catch(SQLException ex) {

System.err.println("SQLException: " + ex.getMessage());

if (con != null) {

try {

System.err.print("Transaction is being ");

System.err.println("rolled back");

con.rollback();

} catch(SQLException excep) {

System.err.print("SQLException: ");

System.err.println(excep.getMessage());

}

}

}

}

/*Creating a Stored procedure involving the coffees and the suppliers table

Page 97: Adv. Java Lab Manual

97

ROHIT BHATIA Advance Java.

08-CSE-133

create procedure SHOW_SUPPLIERS

as

select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME

from SUPPLIERS, COFFEES

where SUPPLIERS.SUP_ID = COFFEES.SUP_ID

order by SUP_NAME

*/

public static void createProcedure1(String userid, String password)

{

String url = "jdbc:odbc:bob";

Connection con;

Statement stmt;

String createProcedure = "create procedure SHOW_SUPPLIERS " +

"as " + "select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME " +

"from SUPPLIERS, COFFEES " + "where SUPPLIERS.SUP_ID =

COFFEES.SUP_ID " +"order by SUP_NAME";

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {

System.err.print("ClassNotFoundException: ");

System.err.println(e.getMessage());}

try {

con = DriverManager.getConnection(url,"DPST_TRNG",

"DPST_TRNG4321");

stmt = con.createStatement();

stmt.executeUpdate(createProcedure);

stmt.close();

con.close();

} catch(SQLException ex) {

System.err.println("SQLException: " + ex.getMessage());

}

}

//Using Callable Statement to call a Stored Procedure

public static void callableDemo(String userid, String password)

{

String url = "jdbc:odbc:bob";

Page 98: Adv. Java Lab Manual

98

ROHIT BHATIA Advance Java.

08-CSE-133

Connection con;

Statement stmt=null;

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {

System.err.print("ClassNotFoundException: ");

System.err.println(e.getMessage());

}

try {con = DriverManager.getConnection(url,"DPST_TRNG",

"DPST_TRNG4321");

CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");

ResultSet rs = cs.executeQuery();

while (rs.next()) {

String c = rs.getString("SUP_NAME");

String s = rs.getString("COF_NAME");

System.out.println(c + " " + s );

}

stmt.close();

con.close();

} catch(SQLException ex) {

System.err.println("SQLException: " + ex.getMessage());

}

}

//A code showing the Batch Update Syntax

public static void batchUpdateDemo(String userid, String password)

{

ResultSet rs = null;

PreparedStatement ps = null;

String url = "jdbc:odbc:bob";

Connection con;

Statement stmt;

try {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {

System.err.print("ClassNotFoundException: ");

System.err.println(e.getMessage());

}

try {

Page 99: Adv. Java Lab Manual

99

ROHIT BHATIA Advance Java.

08-CSE-133

con = DriverManager.getConnection(url,"userid",

"password");

con.setAutoCommit(false);

stmt = con.createStatement();

stmt.addBatch("INSERT INTO COFFEES " +

"VALUES('Amaretto', 49, 9.99, 0, 0)");

stmt.addBatch("INSERT INTO COFFEES " +

"VALUES('Hazelnut', 49, 9.99, 0, 0)");

stmt.addBatch("INSERT INTO COFFEES " +

"VALUES('Amaretto_decaf', 49, 10.99, 0, 0)");

stmt.addBatch("INSERT INTO COFFEES " +

"VALUES('Hazelnut_decaf', 49, 10.99, 0, 0)");

int [] updateCounts = stmt.executeBatch();

con.commit();

con.setAutoCommit(true);

ResultSet uprs = stmt.executeQuery("SELECT * FROM

COFFEES");

System.out.println("Table COFFEES after insertion:");

while (uprs.next()) {

String name = uprs.getString("COF_NAME");

int id = uprs.getInt("SUP_ID");

float price = uprs.getFloat("PRICE");

int sales = uprs.getInt("SALES");

int total = uprs.getInt("TOTAL");

System.out.print(name + " " + id + " " + price);

System.out.println(" " + sales + " " + total);

}

uprs.close();

stmt.close();

con.close();

} catch(BatchUpdateException b) {

System.err.println("-----BatchUpdateException-----");

System.err.println("SQLState: " + b.getSQLState());

System.err.println("Message: " + b.getMessage());

System.err.println("Vendor: " + b.getErrorCode());

System.err.print("Update counts: ");

int [] updateCounts = b.getUpdateCounts();

Page 100: Adv. Java Lab Manual

100

ROHIT BHATIA Advance Java.

08-CSE-133

for (int i = 0; i < updateCounts.length; i++) {

System.err.print(updateCounts[i] + " ");

}

System.err.println("");

} catch(SQLException ex) {

System.err.println("-----SQLException-----");

System.err.println("SQLState: " + ex.getSQLState());

System.err.println("Message: " + ex.getMessage());

System.err.println("Vendor: " + ex.getErrorCode());

}

}

}

Page 101: Adv. Java Lab Manual

101

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 102: Adv. Java Lab Manual

102

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 23

Aim: - Write a program to show use of Action in Applet

program.

Page 103: Adv. Java Lab Manual

103

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.awt.*;

import java.applet.*;

// import an extra class for the ActionListener

import java.awt.event.*;

// Tells the applet you will be using the ActionListener methods.

public class ActionExample extends Applet implements ActionListener

{

Button okButton;

Button wrongButton;

TextField nameField;

CheckboxGroup radioGroup;

Checkbox radio1;

Checkbox radio2;

Checkbox radio3;

public void init()

{

// Now we will use the FlowLayout

setLayout(new FlowLayout());

okButton = new Button("Action!");

wrongButton = new Button("Don't click!");

nameField = new TextField("Type here Something",35);

radioGroup = new CheckboxGroup();

radio1 = new Checkbox("Red", radioGroup,false);

radio2 = new Checkbox("Blue", radioGroup,true);

radio3 = new Checkbox("Green", radioGroup,false);

add(okButton);

add(wrongButton);

add(nameField);

add(radio1);

add(radio2);

add(radio3);

// Attach actions to the components

Page 104: Adv. Java Lab Manual

104

ROHIT BHATIA Advance Java.

08-CSE-133

okButton.addActionListener(this);

wrongButton.addActionListener(this);

}

// Here we will show the results of our actions

public void paint(Graphics g)

{

// If the radio1 box is selected then radio1.getState() will

// return true and this will execute

if (radio1.getState()) g.setColor(Color.red);

// If it was not red we'll try if it is blue

else if (radio2.getState()) g.setColor(Color.blue);

// Since always one radiobutton must be selected it must be green

else g.setColor(Color.green);

// Now that the color is set you can get the text out the TextField

// like this

g.drawString(nameField.getText(),20,100);

}

// When the button is clicked this method will get automatically called

// This is where you specify all actions.

public void actionPerformed(ActionEvent evt)

{

// Here we will ask what component called this method

if (evt.getSource() == okButton)

{

// So it was the okButton, then let's perform his actions

// Let the applet perform Paint again.

// That will cause the aplet to get the text out of the textField

// again and show it.

repaint();

}

// Actions of the wrongButton

else if (evt.getSource() == wrongButton) {

// Change the text on the button for fun

Page 105: Adv. Java Lab Manual

105

ROHIT BHATIA Advance Java.

08-CSE-133

wrongButton.setLabel("Not here!");

// Changes the text in the TextField

nameField.setText("That was the wrong button!");

// Lets the applet show that message.

repaint();

}

}

}

HTML Code

<html>

<body>

<applet code="ActionExample" width=600 height=200>

</applet

</body>

</html>

Page 106: Adv. Java Lab Manual

106

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 107: Adv. Java Lab Manual

107

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 24

Aim: - Write a program to show use of Parameters in Applet

program.

Page 108: Adv. Java Lab Manual

108

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.awt.*;

import java.applet.*;

import java.lang.*;

public class App extends Applet

{

float cel;

double h=1.8;

double far;

public void init()

{

cel= Float.parseFloat(getParameter("C"));

far=cel*h;

}

public void paint(Graphics g){

g.drawString("Farenheit Is:"+far,100,200);

}

}

HTML Code

<html><body>

<applet code="App" width=600 height=200><param name="C"

value="200"

>

</applet>

</body>

Page 109: Adv. Java Lab Manual

109

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 110: Adv. Java Lab Manual

110

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 25

Aim: - Write a program to draw spiral using Applet program.

Page 111: Adv. Java Lab Manual

111

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.applet.*;

import java.awt.*;

import java.lang.Math;

public class ArchimedianSpiral extends Applet {

int width, height;

int N = 30; // number of points per full rotation

int W = 5; // winding number, or number of full rotations

public void init() {

width = getSize().width;

height = getSize().height;

setBackground( Color.black );

setForeground( Color.green );

}

public void paint( Graphics g ) {

int x1 = 0, y1 = 0, x2, y2;

for ( int i = 1; i <= W*N; ++i ) {

double angle = 2*Math.PI*i/(double)N;

double radius = i/(double)N * width/2 / (W+1);

x2 = (int)( radius*Math.cos(angle) );

y2 = -(int)( radius*Math.sin(angle) );

g.drawLine( width/2+x1, height/2+y1, width/2+x2, height/2+y2 );

x1 = x2;

y1 = y2; }

}

}

HTML Code

<html>

<body>

<applet code="ArchimedianSpiral" width=600 height=200>

</applet

</body>

</html>

Page 112: Adv. Java Lab Manual

112

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 113: Adv. Java Lab Manual

113

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 26

Aim: - Write a program to draw lines using Applet program.

Page 114: Adv. Java Lab Manual

114

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.applet.*;

import java.awt.*;

public class DrawingLines extends Applet {

int width, height;

public void init() {

width = getSize().width;

height = getSize().height;

setBackground( Color.black );

}

public void paint( Graphics g ) {

g.setColor( Color.green );

for ( int i = 0; i < 10; ++i ) {

g.drawLine( width, height, i * width / 10, 0 );

}

}

}

HTML Code

<html>

<body>

<applet code="DrawingLines" width=600 height=200>

</applet

</body>

</html>

Page 115: Adv. Java Lab Manual

115

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 116: Adv. Java Lab Manual

116

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 27

Aim: - Write a program to draw image in Applet Program.

Page 117: Adv. Java Lab Manual

117

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

/*

This applet will display a gif on screen

for now the gif file must be in the same directory as this applet

*/

import java.awt.*;

import java.applet.*;

import java.net.*;

public class ImageExample extends Applet

{

// Your image name;

Image my_gif;

// The applet base URL

URL base;

// This object will allow you to control loading

MediaTracker mt;

public void init()

{ // initialize the MediaTracker

mt = new MediaTracker(this);

// The try-catch is necassary when the URL isn't valid

// Ofcourse this one is valid, since it is generated by

// Java itself.

try {

// getDocumentbase gets the applet path.

base = getDocumentBase();

}

catch (Exception e) {}

// Here we load the image.

// Only Gif and JPG are allowed. Transparant gif also.

my_gif = getImage(base,"my_gif.jpg");

// tell the MediaTracker to kep an eye on this image, and give it ID 1;

mt.addImage(my_gif,1);

// now tell the mediaTracker to stop the applet execution

Page 118: Adv. Java Lab Manual

118

ROHIT BHATIA Advance Java.

08-CSE-133

// (in this example don't paint) until the images are fully loaded.

// must be in a try catch block.

try {

mt.waitForAll();

}

catch (InterruptedException e) {}

// when the applet gets here then the images is loaded.

}

public void paint(Graphics g)

{

// now we are going to draw the gif on the screen

// (image name,x,y,observer);

g.drawImage(my_gif,20,20,this);

// you can resize the image easily

g.drawImage(my_gif,20,140,30,40,this);

}

}

HTML Code

<html>

<body>

<applet code="ImageExample" width=600 height=200>

</applet

</body>

</html>

Page 119: Adv. Java Lab Manual

119

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 120: Adv. Java Lab Manual

120

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 28

Aim: - Write a program to show use of Keyboard in Applet

program.

Page 121: Adv. Java Lab Manual

121

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class Keyboard1 extends Applet

implements KeyListener, MouseListener {

int width, height;

int x, y;

String s = "";

public void init() {

width = getSize().width;

height = getSize().height;

setBackground( Color.black );

x = width/2;

y = height/2;

addKeyListener( this );

addMouseListener( this );

}

public void keyPressed( KeyEvent e ) { }

public void keyReleased( KeyEvent e ) { }

public void keyTyped( KeyEvent e ) {

char c = e.getKeyChar();

if ( c != KeyEvent.CHAR_UNDEFINED ) {

s = s + c;

repaint();

e.consume();

}

}

public void mouseEntered( MouseEvent e ) { }

public void mouseExited( MouseEvent e ) { }

public void mousePressed( MouseEvent e ) { }

public void mouseReleased( MouseEvent e ) { }

public void mouseClicked( MouseEvent e ) {

x = e.getX();

y = e.getY();

Page 122: Adv. Java Lab Manual

122

ROHIT BHATIA Advance Java.

08-CSE-133

s = "";

repaint();

e.consume();

}

public void paint( Graphics g ) {

g.setColor( Color.gray );

g.drawLine( x, y, x, y-10 );

g.drawLine( x, y, x+10, y );

g.setColor( Color.green );

g.drawString( s, x, y );

}

}

HTML Code

<html>

<body>

<applet code="Keyboard1" width=600 height=200>

</applet

</body>

</html>

Page 123: Adv. Java Lab Manual

123

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 124: Adv. Java Lab Manual

124

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 29

Aim: - Write a program to show use of Layout in Applet

program.

Page 125: Adv. Java Lab Manual

125

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.awt.*;

import java.applet.*;

public class LayoutExample extends Applet

{

Button okButton1;

Button okButton2;

Button okButton3;

Button okButton4;

Button okButton5;

public void init()

{

// sets the LayoutManager to BorderLayout

setLayout(new BorderLayout());

okButton1 = new Button("Centered");

okButton2 = new Button("North");

okButton3 = new Button("West");

okButton4 = new Button("East");

okButton5 = new Button("South");

add(okButton1,"Center");

add(okButton2,"North");

add(okButton3,"West");

add(okButton4,"East");

add(okButton5,"South");

}

}

HTML Code

<html>

<body>

<applet code="LayoutExample" width=600 height=200>

</applet

</body> </html>

Page 126: Adv. Java Lab Manual

126

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 127: Adv. Java Lab Manual

127

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 30

Aim: - Write a program to show use of Mouse Pointer in

Applet program.

Page 128: Adv. Java Lab Manual

128

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.awt.*;

import java.applet.*;

// import an extra class for the MouseListener

import java.awt.event.*;

// Tells the applet you will be using the MouseListener methods.

public class MouseClickExample extends Applet implements MouseListener

{

// The X-coordinate and Y-coordinate of the last click.

int xpos;

int ypos;

// The coordinates of the rectangle we will draw.

// It is easier to specify this here so that we can later

// use it to see if the mouse is in that area.

int rect1xco,rect1yco,rect1width,rect1height;

// The variable that will tell whether or not the mouse

// is in the applet area.

boolean mouseEntered;

// variable that will be true when the user clicked i the rectangle

// the we will draw.

boolean rect1Clicked;

public void init()

{

// Assign values to the rectanagle coordinates.

rect1xco = 20;

rect1yco = 20;

rect1width = 100;

rect1height = 50;

// Add the MouseListener to your applet

addMouseListener(this);

}

public void paint(Graphics g)

{

// Rectangle's color

g.setColor(Color.green);

Page 129: Adv. Java Lab Manual

129

ROHIT BHATIA Advance Java.

08-CSE-133

g.fillRect(rect1xco,rect1yco,rect1width,rect1height);

g.setColor(Color.red);

// When the user clicks this will show the coordinates of the click

// at the place of the click.

g.drawString("("+xpos+","+ypos+")",xpos,ypos);

// If the click was in the rectangle show this message

if (rect1Clicked) g.drawString("You clicked in the Rectangle",20,120);

// else this one

else g.drawString("You clicked outside of the rectangle",20,120);

if (mouseEntered) g.drawString("Mouse is in the applet area",20,160);

else g.drawString("Mouse is outside the Applet area",20,160);

}

/* These methods always have to present when you implement MouseListener

public void mouseClicked (MouseEvent me) {}

public void mouseEntered (MouseEvent me) {}

public void mousePressed (MouseEvent me) {}

public void mouseReleased (MouseEvent me) {}

public void mouseExited (MouseEvent me) {}

*/

// This method will be called when the mouse has been clicked.

public void mouseClicked (MouseEvent me) {

// Save the coordinates of the click lke this.

xpos = me.getX();

ypos = me.getY();

// Check if the click was inside the rectangle area.

if (xpos > rect1xco && xpos < rect1xco+rect1width && ypos >rect1yco

&& ypos < rect1yco+rect1height)

rect1Clicked = true;

// if it was not then rect1Clicked is false;

else

rect1Clicked = false;

//show the results of the click

repaint();

}

// This is called when the mous has been pressed

Page 130: Adv. Java Lab Manual

130

ROHIT BHATIA Advance Java.

08-CSE-133

public void mousePressed (MouseEvent me) {}

// When it has been released

// not that a click also calls these Mouse-Pressed and Released.

// since they are empty nothing hapens here.

public void mouseReleased (MouseEvent me) {}

// This is executed when the mouse enters the applet. it will only

// be executed again when the mouse has left and then re-entered.

public void mouseEntered (MouseEvent me) {

// Will draw the "inside applet message"

mouseEntered = true;

repaint();

}

// When the Mouse leaves the applet.

public void mouseExited (MouseEvent me) {

// will draw the "outside applet message"

mouseEntered = false;

repaint();

}

}

HTML Code

<html>

<body>

<applet code="MouseClickExample" width=600 height=200>

</applet

</body>

</html>

Page 131: Adv. Java Lab Manual

131

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 132: Adv. Java Lab Manual

132

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 31

Aim: - Write a program to print number using loop in Applet

program.

Page 133: Adv. Java Lab Manual

133

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.awt.*;

import java.applet.*;

public class PrintNum extends Applet implements Runnable

{

public void run()

{}

public void paint(Graphics g){

try {

Thread.sleep(100);

for(int i=1; i<=10; i++)

g.drawString(String.valueOf(i), 10, 5 + i* 20); }

catch (InterruptedException e)

{ }

}

}

HTML Code

<html>

<body>

<applet code="PrintNum" width=600 height=200>

</applet

</body>

</html>

Page 134: Adv. Java Lab Manual

134

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT

Page 135: Adv. Java Lab Manual

135

ROHIT BHATIA Advance Java.

08-CSE-133

Practical No: - 32

Aim: - Write a program to show Hello World in Applet program.

Page 136: Adv. Java Lab Manual

136

ROHIT BHATIA Advance Java.

08-CSE-133

PROGRAM

import java.applet.*;

import java.awt.*;

public class HelloWorld extends Applet

{

public void init()

{

}

public void stop()

{

}

public void paint(Graphics g)

{

g.drawString("Welcome to java programming",30,30);

g.drawString("Hellllo World!!!!",50,50);

}

}

HTML Code

<html>

<body>

<applet code="HelloWorld" width=600 height=200>

</applet

</body>

</html>

Page 137: Adv. Java Lab Manual

137

ROHIT BHATIA Advance Java.

08-CSE-133

OUTPUT