Java Lab Solutions
-
Upload
pradeep-tiwari -
Category
Documents
-
view
317 -
download
6
Transcript of Java Lab Solutions
-
8/6/2019 Java Lab Solutions
1/34
// 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
1
-
8/6/2019 Java Lab Solutions
2/34
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)
{}
}
}
2
2
-
8/6/2019 Java Lab Solutions
3/34
// 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
-
8/6/2019 Java Lab Solutions
4/34
// 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 volumedouble 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 boxvol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
4
4
-
8/6/2019 Java Lab Solutions
5/34
// 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);}
}
5
5
-
8/6/2019 Java Lab Solutions
6/34
//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);}
}
6
6
-
8/6/2019 Java Lab Solutions
7/34
// 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);
}
}
}
7
7
-
8/6/2019 Java Lab Solutions
8/34
// 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
8
-
8/6/2019 Java Lab Solutions
9/34
catch(Exception e)
{
System.out.println("Exception caught");
}
procB();
procC();}
}
9
9
-
8/6/2019 Java Lab Solutions
10/34
// 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
-
8/6/2019 Java Lab Solutions
11/34
//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
-
8/6/2019 Java Lab Solutions
12/34
System.out.println("********************");
//Arrays.sort(name);
Arrays.sort(name, Collections.reverseOrder());
for (int i=0; i
-
8/6/2019 Java Lab Solutions
13/34
// 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
13
-
8/6/2019 Java Lab Solutions
14/34
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
14
-
8/6/2019 Java Lab Solutions
15/34
// 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
15
-
8/6/2019 Java Lab Solutions
16/34
// 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
16
-
8/6/2019 Java Lab Solutions
17/34
// 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
17
-
8/6/2019 Java Lab Solutions
18/34
// 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
18
-
8/6/2019 Java Lab Solutions
19/34
}
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
19
-
8/6/2019 Java Lab Solutions
20/34
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
20
-
8/6/2019 Java Lab Solutions
21/34
// 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
-
8/6/2019 Java Lab Solutions
22/34
System.out.println(c);
} while (c != 'q');
}
}
// Read a string from console using a BufferedReaderimport 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
22
-
8/6/2019 Java Lab Solutions
23/34
// 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
-
8/6/2019 Java Lab Solutions
24/34
// 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
24
-
8/6/2019 Java Lab Solutions
25/34
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
25
-
8/6/2019 Java Lab Solutions
26/34
// 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
26
-
8/6/2019 Java Lab Solutions
27/34
// 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
27
-
8/6/2019 Java Lab Solutions
28/34
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
28
-
8/6/2019 Java Lab Solutions
29/34
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
29
-
8/6/2019 Java Lab Solutions
30/34
{
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
/*
*/
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
30
-
8/6/2019 Java Lab Solutions
31/34
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
31
-
8/6/2019 Java Lab Solutions
32/34
// Applets
// A Simple 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
/*
*/
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
32
-
8/6/2019 Java Lab Solutions
33/34
// Font Metrics
/*
*/
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
/*
*/
import java.applet.Applet;
import java.awt.*;
public class ImageDemo extends Applet
{Image img;
public void init ( )
33
33
-
8/6/2019 Java Lab Solutions
34/34
{
img=getImage(getCodeBase(),"rabbit.gif");
}
public void paint (Graphics g)
{
g.drawImage(img,10,10,this);
}}
// Passing Parameters
/*
*/
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