0% found this document useful (0 votes)
612 views34 pages

Java Lab Solutions

The document contains 14 code snippets in Java that demonstrate various Java concepts like classes, objects, inheritance, exceptions, strings, arrays, and more. The code snippets include programs to calculate square, check if a number is Armstrong, calculate factorial, find prime numbers, use constructors and parameterized constructors to initialize objects, method overloading, throw and throws exceptions, use finally block, string methods, sort arrays, inheritance, and polymorphism.

Uploaded by

Pradeep Tiwari
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
0% found this document useful (0 votes)
612 views34 pages

Java Lab Solutions

The document contains 14 code snippets in Java that demonstrate various Java concepts like classes, objects, inheritance, exceptions, strings, arrays, and more. The code snippets include programs to calculate square, check if a number is Armstrong, calculate factorial, find prime numbers, use constructors and parameterized constructors to initialize objects, method overloading, throw and throws exceptions, use finally block, string methods, sort arrays, inheritance, and polymorphism.

Uploaded by

Pradeep Tiwari
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 34

1 // Program to calculate the Square of a number. import java.io.

*; class Square1 { public static void main(String args[]) { try { int a,s; String line; System.out.println("Enter the required value:"); BufferedReader d=new BufferedReader(new InputStreamReader(System.in)); line =d.readLine(); a = Integer.parseInt(line); s = a*a; System.out.println(s); } catch(IOException e) {} } } //Program to print the entered number is Armstrong number or not import java.io.*; class Armstrong { public static void main(String arg[]) { try { int a,b,c,e; String line; System.out.println("Enter the required value:"); BufferedReader d=new BufferedReader(new InputStreamReader(System.in)); line =d.readLine(); a = Integer.parseInt(line); b = 0; c = 0; e = a; int factorial=1; while (a != 0) { b = a % 10; c = c + b * b * b; a = a / 10; } 1

2 if (e == c) { System.out.print("Armstrong Number "); } else { System.out.print("Not Armstrong"); } } catch(IOException e) {} } } // Program to calculate the Factorial of a number import java.io.*; class Fact { public static void main(String arg[]) { try { int a,s; String line; System.out.println("Enter the required value:"); BufferedReader d=new BufferedReader(new InputStreamReader(System.in)); line =d.readLine(); a = Integer.parseInt(line); int factorial=1; for (int i = a; i > 0; i--) { factorial = factorial * i; } System.out.print("factorial of " + a); System.out.print(" = " + factorial); } catch(IOException e) {} } }

3 // Program to print Prime numbers from 1 to 100. class Prime { public static void main(String[] args) { int i=1,j; int flag=0; for (i=2;i<100;i++) { flag=0; for (j=2;j<=(i/2);j++) { if(i%j==0 && j!=i) { flag=1; break; } } if (flag!=1) System.out.print("\t"+i); } } }

4 // Box uses a constructor to initialize the dimensions of a box class Box { double width; double height; double depth; // This is the constructor for Box Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } // Compute and return volume double volume() { return width * height * depth; } } class BoxDemo { public static void main(String[] args) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // Get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // Get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } }

5 // Here, Box uses parameterized constructor to initialize the dimensions of a box class Box { double width; double height; double depth; // This is the constructor for Box Box(double w, double h, double d) { width = w; height = h; depth = d; } // Compute and return volume double volume() { return width * height * depth; } } class BoxDemoParam { public static void main(String[] args) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(3, 6, 9); double vol; // Get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // Get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } }

6 //Method Overloading and parameter passing class Overloadtest { void test() { System.out.println("No Parameters"); } //Overload test for one integer parameter void test(int a) { System.out.println("a: " + a); } //Overload test for two integer parameters void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } //Overload test for double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { Overloadtest t = new Overloadtest(); double result; //Call all versions of test() t.test(); t.test(10); t.test(10,20); result = t.test(125.25); System.out.println("Result of t.test(125.25): " + result); } }

// Using throw exception class Throwdemo { static void demoproc() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside demoproc"); throw e; } } public static void main(String args[]){ try { demoproc(); } catch(NullPointerException e){ System.out.println("Recaught:"+e); } } } // Using throws class ThrowsDemo { static void throwsOne() throws IllegalAccessException { System.out.println("Inside throwOne"); throw new IllegalAccessException("Demo"); } public static void main(String args[]) { try { throwsOne(); }catch(IllegalAccessException e) { System.out.println("Caught" +e); } } }

8 // Using finally import java.io.*; class FinallyDemo { static void procA() { try { System.out.println("Inside procA"); throw new RuntimeException ("Demo"); } finally { System.out.println("procA's finally"); } } //Return from within a try block static void procB() { try { System.out.println("Inside procB"); return; } finally { System.out.println("procB's finally"); } } //Execute a try block normally static void procC() { try { System.out.println("Inside procC"); } finally { System.out.println("procC's finally"); } } public static void main(String args[]) { try { procA(); } 8

9 catch(Exception e) { System.out.println("Exception caught"); } procB(); procC(); } }

10 // Using String methods class Stringdemo { public static void main(String[] args) { String str1="Hello everyone, great day "; String str2="World"; String str4=str1; String str3[]= {"ONE","TWO","THREE","FOUR"}; for(int i=0 ; i<str3.length; i++) { System.out.println("str[ " + i +" ]:" +str3[i]); } System.out.println("length of str1:" + str1.length()); System.out.println( str2.concat(" great ")); System.out.println("substring of str1:" + str1.substring(6)); System.out.println("substring of str1:" + str1.substring(6,14)); System.out.println("replace in str2:" + str2.replace('r','m')); System.out.println("lower str1:" + str1.toLowerCase()); System.out.println("lower str2:" + str2.toUpperCase()); System.out.println("substring of str1 trim:" + str1.trim()); System.out.println("char at index[4] of str1:" + str1.charAt(4)); System.out.println("char at first index of str1:" + str1.indexOf('e')); System.out.println("char at last index of str1 (e):" + str1.lastIndexOf('e')); if(str1.equals(str2)) System.out.println("str1 == str2"); else System.out.println("str1 != str2"); if(str1.equals(str4)) System.out.println("str1 == str4"); else System.out.println("str1 != str4"); } }

10

11 //Program to Sort an Array of string in an Ascending order import java.util.Arrays; class SortString { public static void main(String[] args) { String name[] = new String[6]; name[0] = "Neeta"; name[1] = "Seeta"; name[2] = "Mohan"; name[3] = "Ashim"; name[4] = "Shama"; name[5] = "Geeta"; System.out.println("Array Before Sorting"); System.out.println("********************"); for (int i=0; i<6; i++) { System.out.println("name " + i + " : " + name[i]); } System.out.println(""); System.out.println("Array After Sorting"); System.out.println("********************"); Arrays.sort(name); for (int i=0; i<6; i++) { System.out.println("name " + i + " : " + name[i]); } } } //Program to sort an array of strings in Descending order import java.util.Arrays; import java.util.Collections; class SortStringDes { public static void main(String[] args) { String name[] = new String[6]; name[0] = "Neeta"; name[1] = "Seeta"; name[2] = "Mohan"; name[3] = "Ashim"; name[4] = "Shama"; name[5] = "Geeta"; System.out.println("Array Before Sorting"); System.out.println("********************"); for (int i=0; i<6; i++) { System.out.println("name " + i + " : " + name[i]); } System.out.println(""); System.out.println("Array After Sorting"); 11

12 System.out.println("********************"); //Arrays.sort(name); Arrays.sort(name, Collections.reverseOrder()); for (int i=0; i<6; i++) { System.out.println("name " + i + " : " + name[i]); } } } //Program to sort an array of strings in Descending order import java.util.Arrays; import java.util.Collections; class SortStringDes1 { public static void main(String[] args) { //String[] name = new String[6]; String[] name = new String[] {"Neeta", "Seeta", "Mohan", "Ashim", "Shama", "Geeta"}; System.out.println("Array Before Sorting"); System.out.println("********************"); for (int i=0; i<6; i++) { System.out.println("name " + i + " : " + name[i]); } System.out.println(""); System.out.println("Array After Sorting"); System.out.println("********************"); //Arrays.sort(name); Arrays.sort(name, Collections.reverseOrder()); for (int i=0; i<6; i++) { System.out.println("name " + i + " : " + name[i]); } } } // Program to print reverse of a string using charAt() import java.io.*; public class StringRev { public static void main (String [] args) throws IOException { String s = args[0]; for (int i=s.length() -1;i>=0;i-- ) { System.out.println(s.charAt(i)); } } } 12

13 // Using Inheritance class Info { protected String name="sahil"; protected String addr="9 ,vile parle (E)"; } class Info1 extends Info { private int age=22; public void disp1() { System.out.println("name :" + name); System.out.println("address :" + addr); System.out.println("age is :" + age); } public static void main(String args[]) { Info1 i1= new Info1(); i1.disp1(); } } import java.io.*; class books { protected String aut; protected String name; void getDet() { //super.getDet(); try { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter author name"); aut=br.readLine(); System.out.println("enter book name"); name=br.readLine(); } catch(IOException e) {} } void showDet() { //super.showDet(); System.out.println("showing book details..."); 13

14 System.out.println("==============="); System.out.println("author :" + aut); System.out.println("bookname :" + name); } } import java.io.*; class Category extends books { private String catcode; void getDet() { super.getDet(); try { BufferedReader br=new BufferedReader (new InputStreamReader(System.in)); System.out.println("enter category code"); catcode=br.readLine(); } catch(IOException e) {} } void showDet() { super.showDet(); System.out.println("showing category details..."); System.out.println("======================"); System.out.println("Category code:" + catcode); } public static void main(String args[]) { Category c=new Category(); c.getDet(); c.showDet(); } }

14

15 // Interfaces public interface Test { public int square(int a); } class Arithmetic implements Test { int s = 0; public int square(int b) { s = b * b; System.out.println("Inside Arithmetic class implemented method square"); System.out.println("Square of " + b + " is " + s); return s; } void armeth() { System.out.println("Inside method of class Arithmetic"); } } class ToTestInt { public static void main(String args[]) { System.out.println("Calling... from ToTestInt class main method"); Test t = new Arithmetic(); System.out.println("==========================="); System.out.println("Created object of test interface - reference Arithmetic class"); System.out.println("Hence Arithmetic class method square called"); System.out.println("This object cannot call armeth method of Arithmetic class"); System.out.println("==========================="); t.square(10); System.out.println("==========================="); } }

15

16 // Package // Create a folder Pack and write the following code in this folder package Pack; public class Class1 { public static void greet() { System.out.println("Hello"); } } // Create a folder Subpack in a Pack folder and write the following code in this folder package Pack.Subpack; public class Class2 { public static void farewell() { System.out.println("bye"); } } // Come out of both the folders and write the following code // Importing Packages import Pack.*; import Pack.Subpack.*; class Importer { public static void main(String arg[]) { Class1.greet(); Class2.farewell(); } }

16

17 // Multithreading //to illustrate creation of threads using class Thread class MyThread extends Thread { MyThread() { // super ("Using Thread class"); System.out.println("Child thread :"+this); start(); } public void run() { try { for (int i=5;i >0;i--) { System.out.println("Child thread :"+i); Thread.sleep(500); } }catch (InterruptedException e){} System.out.println("Exiting Child thread .."); } } class TestMyThread { public static void main(String args[]) { new MyThread(); try { for (int k=5;k >0;k--) { System.out.println("Running main thread :"+k); Thread.sleep(1000); } }catch (InterruptedException e){} System.out.println(" Exiting Main thread.."); } }

17

18 // Using Thread methods class ThreadMethod1{ public static void main(String args[]){ Thread t=Thread.currentThread(); System.out.println("current thread:"+t); System.out.println("Name of the current thread:"+t.getName()); System.out.println("Priority:"+t.getPriority()); t.setName("mythread"); System.out.println("after name change:"+t); t.setPriority(2); System.out.println("after priority change:"+t); System.out.println("number of active threads:"+t.activeCount()); } } // Without Synchronization class Callme { void call (String msg) { System.out.print("[" + msg); try { Thread.sleep(1000); } catch (InterruptedException e){ System.out.println("Interrupted"); } System.out.println("]"); } } class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ, String s) { target = targ; msg = s; t = new Thread(this); t.start(); } public void run() { target.call(msg); } 18

19 } class Synch { public static void main(String[] args) { Callme target = new Callme(); Caller ob1 = new Caller(target, "Hello"); Caller ob2 = new Caller(target, "Synchronized"); Caller ob3 = new Caller(target, "World"); // wait for a threads to end try { ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch(InterruptedException e) { System.out.println("Interrupted"); } } } // With Synchronization class Callme { void call (String msg) { System.out.print("[" + msg); try { Thread.sleep(1000); } catch (InterruptedException e){ System.out.println("Interrupted"); } System.out.println("]"); } } class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ, String s) { target = targ; msg = s; t = new Thread(this); 19

20 t.start(); } public void run() { synchronized(target) // Synchronized block { target.call(msg); } } } class Synch { public static void main(String[] args) { Callme target = new Callme(); Caller ob1 = new Caller(target, "Hello"); Caller ob2 = new Caller(target, "Synchronized"); Caller ob3 = new Caller(target, "World"); // wait for a threads to end try { ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch(InterruptedException e) { System.out.println("Interrupted"); } } }

20

21 // Java.io Package io streams import java.io.*; class ByteArray { public static void main(String args [ ] ) throws Exception { ByteArrayOutputStream f = new ByteArrayOutputStream(10); System.out.println("enter 10 characters and press the Enter key"); System.out.println("These will be converted to uppercase and displayed"); while (f.size( ) != 10) { f.write(System.in.read( ) ); } System.out.println("Accepted characters into an array"); byte b[ ] = f.toByteArray( ); System.out.println("displaying characters in the array"); for(int l=0; l<b.length; l++) { System.out.println( (char) b [l]); } ByteArrayInputStream inp = new ByteArrayInputStream(b); int c; System.out.println("converted to upper case characters"); for (int i=0;i<1;i++) { while ( (c = inp.read( )) != -1) { System.out.print("\n" + c); System.out.print(Character.toUpperCase( (char)c) ); } System.out.println( ); inp.reset( ); } } } // Use a BufferedReader to read characters from the console import java.io.*; class BRRead { public static void main(String[] args) throws IOException { char c; BufferedReader br = new BufferedReader(new InputStreamReader (System.in)); System.out.println("Enter Characters, 'q' to quit."); //Read characters do { c = (char)br.read(); 21

22 System.out.println(c); } while (c != 'q'); } } // Read a string from console using a BufferedReader import java.io.*; class BRReadLines { public static void main(String[] args) throws IOException { // create a BufferedReader using System.in String str; BufferedReader br = new BufferedReader(new InputStreamReader (System.in)); System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); do { str = br.readLine(); System.out.println(str); } while (!str.equals("stop")); } } import java.io.*; class DataStream { public static void main(String args[ ]) throws IOException { BufferedReader d=new BufferedReader(new InputStreamReader(new FileInputStream("c:/SemIV/IOPackage/temp.txt"))); DataOutputStream o=new DataOutputStream(new FileOutputStream("c:/SemIV/IOPackage/temp")); String line; while((line=d.readLine()) !=null) { String a=(line.toUpperCase()); System.out.println(a); o.writeBytes(a); } d.close(); o.close(); } }

22

23 // Reading and Writing to and from a file import java.io.*; class ReadWriteFile { public static byte getInput ( )[ ] throws Exception { byte inp[ ] = new byte[50]; System.out.println("enter text."); System.out.println("only 50 bytes i.e. about 2 lines ..."); System.out.println("press enter after each line to get input into the program"); for (int i=0;i<50;i++) { inp[i] = (byte) System.in.read( ); } return inp; } public static void main(String args[ ]) throws Exception { byte input[ ] = getInput( ); OutputStream f = new FileOutputStream("c:/SemIV/IOPackage/write1.txt"); for (int i=0;i<50;i++) { f.write(input[i]); } f.close( ); int size; InputStream f1 = new FileInputStream("c:/SemIV/IOPackage/write1.txt"); size = f1.available( ); System.out.println("reading contents of file write1.txt ..."); for (int i=0;i<size;i++) { System.out.println( (char)f1.read( ) ); } f.close( ); } }

23

24 // Swings and Layout Managers // Buttons import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Button1 extends JFrame implements ActionListener { JButton mtextbtn1; JButton mtextbtn2; JButton mtextbtn3; JButton mtextbtn4; JButton mtextbtn5; public Button1() { setTitle("BUTTON EXAMPLE"); JPanel contentpane = (JPanel)getContentPane(); contentpane.setLayout(new FlowLayout()); //contentpane.setLayout(new GridLayout(2,3)); mtextbtn1 = new JButton("Enabled"); mtextbtn1.setMnemonic('E'); mtextbtn1.addActionListener(this); contentpane.add(mtextbtn1); mtextbtn2 = new JButton("Disabled"); mtextbtn2.setMnemonic('D'); mtextbtn2.addActionListener(this); contentpane.add(mtextbtn2); mtextbtn3 = new JButton("Add"); mtextbtn3.setMnemonic('A'); mtextbtn3.addActionListener(this); contentpane.add(mtextbtn3); mtextbtn4 = new JButton("Fourth"); mtextbtn4.setMnemonic('F'); mtextbtn4.addActionListener(this); contentpane.add(mtextbtn4); mtextbtn5 = new JButton("Fifth"); mtextbtn5.setMnemonic('T'); mtextbtn5.addActionListener(this); contentpane.add(mtextbtn5); mtextbtn1.setEnabled(true); myadapter myapp = new myadapter(); addWindowListener(myapp); }

24

25

class myadapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } public void actionPerformed(ActionEvent e) { if(e.getSource() == mtextbtn1) { setTitle("First Button Clicked"); } else if (e.getSource() == mtextbtn2) { setTitle("Second Button Clicked"); } else if (e.getSource() == mtextbtn3) { setTitle("Add Button Clicked"); } else if (e.getSource() == mtextbtn4) { setTitle("Fourth Button Clicked"); } else if (e.getSource() == mtextbtn5) { setTitle("Fifth Button Clicked"); } } public static void main(String args[]) { Button1 b = new Button1(); b.setSize(100,100); b.setVisible(true); } }

25

26 // Labels import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Labels extends JFrame { JLabel j1,j2,j3,j4; public Labels() { JPanel contentpane = (JPanel)getContentPane(); contentpane.setLayout(new GridLayout(4,1)); setTitle("Label Example"); j1 = new JLabel ("First label"); j1.setFont(new Font("Arial",Font.PLAIN,14)); contentpane.add(j1); j2 = new JLabel("Just Text"); j2.setFont(new Font("Serif",Font.BOLD,10)); contentpane.add(j2); j3 = new JLabel("can display an imag here"); j3.setFont(new Font("TimesRoman",Font.ITALIC,12)); contentpane.add(j3); j4 = new JLabel("Last label to be created"); j4.setFont(new Font("SansSerif",Font.BOLD+Font.ITALIC,16)); contentpane.add(j4); myadapter myapp=new myadapter(); addWindowListener(myapp); } class myadapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } public static void main(String args[]) { Labels lbl = new Labels(); lbl.setSize(250,250); lbl.setVisible(true); } }

26

27 // Text field import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.text.*; public class Textf extends JFrame { JTextField la; public Textf() { setTitle("Text Field instance"); JPanel contentpane = (JPanel)getContentPane(); contentpane.setLayout(new FlowLayout()); la = new JTextField(25); la.setFont(new Font("Arial",Font.PLAIN,14)); contentpane.add(la); myadapter myapp = new myadapter(); addWindowListener(myapp); } class myadapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } public static void main(String args[]) { Textf tt = new Textf(); tt.setSize(250,250); tt.setVisible(true); } } // Text area import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.text.*; public class Textarea extends JFrame { JTextArea jtx; public Textarea() { JPanel contentpane = (JPanel)getContentPane(); contentpane.setLayout(new BorderLayout()); 27

28 setTitle("Text Area Example"); jtx = new JTextArea(); jtx.setFont(new Font("Arial",Font.PLAIN,14)); contentpane.add("Center",jtx); //contentpane.add("East",jtx); JLabel j1; j1 = new JLabel ("First label"); j1.setFont(new Font("Arial",Font.BOLD,14)); contentpane.add("North",j1); // JLabel j2= new JLabel ("status bar"); j2.setFont(new Font("Arial",Font.BOLD,14)); contentpane.add("South",j2); myadapter myapp = new myadapter(); addWindowListener(myapp); } class myadapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } public static void main(String args[]) { Textarea tx = new Textarea(); tx.setSize(150,150); tx.setVisible(true); } } //Check box import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Checkbox extends JFrame implements ItemListener { JCheckBox cbox; public Checkbox() { setTitle("Check Box Example"); JPanel contentpane = (JPanel)getContentPane(); contentpane.setLayout(new GridLayout(1, 1)); cbox = new JCheckBox("Toggle"); cbox.addItemListener(this); contentpane.add(cbox); 28

29 myadapter myapp = new myadapter(); addWindowListener(myapp); } class myadapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } public void itemStateChanged(ItemEvent e) { if(e.getStateChange() == ItemEvent.SELECTED) setTitle("Checkbox selected"); else setTitle("Checkbox unselected"); } public static void main(String args[]) { Checkbox c = new Checkbox(); c.setVisible(true); c.setSize(100,100); } } // Radio buttons import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Checkbox extends JFrame implements ItemListener { JCheckBox cbox; public Checkbox() { setTitle("Check Box Example"); JPanel contentpane = (JPanel)getContentPane(); contentpane.setLayout(new GridLayout(1, 1)); cbox = new JCheckBox("Toggle"); cbox.addItemListener(this); contentpane.add(cbox); myadapter myapp = new myadapter(); addWindowListener(myapp); } class myadapter extends WindowAdapter { public void windowClosing(WindowEvent e) 29

30 { System.exit(0); } } public void itemStateChanged(ItemEvent e) { if(e.getStateChange() == ItemEvent.SELECTED) setTitle("Checkbox selected"); else setTitle("Checkbox unselected"); }

public static void main(String args[]) { Checkbox c = new Checkbox(); c.setVisible(true); c.setSize(100,100); } } // Menu creation /* <applet code = "UseMenu" width = 300 height = 200 > </applet> */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class UseMenu extends JApplet { public void init() { Container cont = this.getContentPane(); cont.setLayout(new BorderLayout()); JMenuBar mb = new JMenuBar(); cont.add(mb, BorderLayout.NORTH); JMenu file = new JMenu("File"); file.add(new JMenuItem("New")); file.add(new JMenuItem("Open")); file.addSeparator(); file.add(new JMenuItem("Save") ); file.add(new JMenuItem("Close") ); mb.add(file); 30

31 JMenu edit = new JMenu("Edit"); edit.add(new JMenuItem("Undo")); edit.add(new JMenuItem("Redo")); edit.addSeparator(); edit.add(new JMenuItem("Cut Ctrl+X")); edit.add(new JMenuItem("Copy Ctrl+C;")); edit.add(new JMenuItem("Paste Ctrl+V")); edit.add(new JMenuItem("Select All")); // creating a sub menu JMenu clear = new JMenu("clear"); clear.add(new JMenuItem("All")); clear.add(new JMenuItem("Format")); clear.add(new JMenuItem("Contents")); edit.add(clear); mb.add(edit); } }

31

32 // Applets // A Simple Applet /* <applet code="Applets1.class" width=250 height=120> </applet>*/ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Applets1 extends JApplet { JButton but1; public void init() { JPanel contentpane = (JPanel)getContentPane(); but1 = new JButton("Displayed in an Applet"); contentpane.add(but1); } } // A Simple Applet /* <applet CODE="SmileApplet.class" width=250 height=250> </APPLET> */ import java.awt.*; import java.applet.Applet; import java.awt.event.*; public class SmileApplet extends Applet implements MouseMotionListener { public void init( ) { addMouseMotionListener(this); } public void paint(Graphics g) { Font f = new Font ("Helvetica",Font.BOLD,20); g.setFont(f); g.drawString("always keep smiling !!",50,30); g.drawOval(60,60,200,200); g.fillOval(90,120,50,20); g.fillOval(190,120,50,20); g.drawLine(165,125,165,175); g.drawArc(110,130,95,95,0,-180); g.drawLine(165,175,150,160); } public void mouseMoved(MouseEvent e) { showStatus("" + e.getX( ) + "," + e.getY( ) ); } public void mouseDragged (MouseEvent e) {} } 32

33 // Font Metrics /* <applet CODE="fontMetrics.class" width=250 height=250> </APPLET> */ import java.applet.*; import java.awt.*; public class fontMetrics extends Applet { Font f1,f2; int ascent, descent, height, leading; String one,two,three,four; public void init ( ) { f1 = new Font("Helvetica", Font.BOLD,14); f2 = new Font("TimesRoman", Font.BOLD+Font.ITALIC,12); } public void paint (Graphics g) { g.setFont (f1); ascent = g.getFontMetrics( ).getAscent( ); descent = g.getFontMetrics( ).getDescent( ); height = g.getFontMetrics( ).getHeight( ); leading = g.getFontMetrics( ).getLeading( ); one = "Ascent of font f1 is: " + ascent; two = "Descent of font f1 is: " + descent; three = "Leading of font f1 is: " + leading; four = "Height of font f1 is: " + height; g.drawString(one, 20,20); g.drawString(two, 20,50); g.drawString(three,20,80); g.drawString(four, 20,110); } } // Image demo /* <applet CODE="ImageDemo.class" width=250 height=250> </APPLET> */ import java.applet.Applet; import java.awt.*; public class ImageDemo extends Applet { Image img; public void init ( ) 33

34 { img=getImage(getCodeBase(),"rabbit.gif"); } public void paint (Graphics g) { g.drawImage(img,10,10,this); } } // Passing Parameters /* <applet CODE="ParamApp.class" width=250 height=250> <align=top> <PARAM NAME=name value="Raj"> </APPLET> */ import java.awt.*; public class ParamApp extends java.applet.Applet { Font f = new Font("TimesNewRoman",Font.BOLD, 40); String name; public void init() { name = getParameter("name"); if (name == null) name = "friend"; name="have a nice day dear " + name; } public void paint(Graphics g) { g.setFont(f); g.setColor(Color.darkGray); g.drawString(name,50,50); } }

34

You might also like