Archive for June 2015
class StringDemo
{
public static void main (String args[])
{
String str = "I am vijay";
System.out.println("The string is: " + str);
System.out.println("The string in upper case: " + str.toUpperCase());
System.out.println("Length of this string: " + str.length());
System.out.println("The character at position 5: "+ str.charAt(5));
System.out.println("The index of the character y: " + str.indexOf('y'));
System.out.println("The substring from 2 to 10: " + str.substring(2, 10));
System.out.println("The index of the beginning of the substring vijay: " + str.indexOf("vijay"));
}
}
{
public static void main (String args[])
{
String str = "I am vijay";
System.out.println("The string is: " + str);
System.out.println("The string in upper case: " + str.toUpperCase());
System.out.println("Length of this string: " + str.length());
System.out.println("The character at position 5: "+ str.charAt(5));
System.out.println("The index of the character y: " + str.indexOf('y'));
System.out.println("The substring from 2 to 10: " + str.substring(2, 10));
System.out.println("The index of the beginning of the substring vijay: " + str.indexOf("vijay"));
}
}
Output:
The string is: I am vijay
The string in upper case: I AM VIJAY
Length of this string: 10
The character at position 5: v
The index of the character y: 9
The substring from 2 to 10: am vijay
The index of the beginning of the substring vijay: 5
The string in upper case: I AM VIJAY
Length of this string: 10
The character at position 5: v
The index of the character y: 9
The substring from 2 to 10: am vijay
The index of the beginning of the substring vijay: 5
class arithmetic
{
public static void main(String args[])
{
short x = 8;
int y = 2;
float a = 10.5f;
float b = 6f;
System.out.println("Addition: "+(x+y));
System.out.println("Subtraction: "+(x-y));
System.out.println("Multiplication: "+(x*y));
System.out.println("Division: "+(x/y));
System.out.println("Modulus: "+(x%y));
System.out.println("Floating point Division: "+(a/b));
}
}
{
public static void main(String args[])
{
short x = 8;
int y = 2;
float a = 10.5f;
float b = 6f;
System.out.println("Addition: "+(x+y));
System.out.println("Subtraction: "+(x-y));
System.out.println("Multiplication: "+(x*y));
System.out.println("Division: "+(x/y));
System.out.println("Modulus: "+(x%y));
System.out.println("Floating point Division: "+(a/b));
}
}
Output:
Addition: 10
Subtraction: 6
Multiplication: 16
Division: 4
Modulus: 0
Floating point Division: 1.75
Subtraction: 6
Multiplication: 16
Division: 4
Modulus: 0
Floating point Division: 1.75
Syntax:
if(condition 1)
statement 1;
else if (condition 2)
statement 2;
else if (condition 3)
statement 3;
statement 1;
else if (condition 2)
statement 2;
else if (condition 3)
statement 3;
else
statement 4;
Grade System Program:
import java.util.Scanner;
class result
{
public static void main(String[] args)
{
int mark;
Scanner s=new Scanner(System.in);
System.out.print("Enter your mark: ");
mark=s.nextInt();
if ( mark >= 90 )
{
System.out.println( "Grade A" );
}
else if ( mark >= 80 )
{
System.out.println( "Grade B" );
}
else if ( mark >= 70 )
{
System.out.println( "Grade C" );
}
else if ( mark >= 60 )
{
System.out.println( "Grade D" );
}
else if ( mark >= 50 )
{
System.out.println( "Grade E" );
}
else if ( mark >= 40 )
{
System.out.println( "Grade F" );
}
else
{
System.out.println( "Failed" );
}
}
}
class result
{
public static void main(String[] args)
{
int mark;
Scanner s=new Scanner(System.in);
System.out.print("Enter your mark: ");
mark=s.nextInt();
if ( mark >= 90 )
{
System.out.println( "Grade A" );
}
else if ( mark >= 80 )
{
System.out.println( "Grade B" );
}
else if ( mark >= 70 )
{
System.out.println( "Grade C" );
}
else if ( mark >= 60 )
{
System.out.println( "Grade D" );
}
else if ( mark >= 50 )
{
System.out.println( "Grade E" );
}
else if ( mark >= 40 )
{
System.out.println( "Grade F" );
}
else
{
System.out.println( "Failed" );
}
}
}
Output:
Enter your mark: 56
Grade E
Enter your mark: 10
Failed
Syntax:
if(condition)
statement 1;
else
statement 2;
statement 1;
else
statement 2;
Program:
import java.util.Scanner;
class result
{
public static void main(String[] args)
{
int mark;
Scanner s=new Scanner(System.in);
System.out.print("Enter your mark: ");
mark=s.nextInt();
if ( mark <= 60 )
{
System.out.println("Fail");
}
else
{
System.out.println("Pass");
}
}
}
class result
{
public static void main(String[] args)
{
int mark;
Scanner s=new Scanner(System.in);
System.out.print("Enter your mark: ");
mark=s.nextInt();
if ( mark <= 60 )
{
System.out.println("Fail");
}
else
{
System.out.println("Pass");
}
}
}
Output:
Enter your mark: 23
Fail
Enter your mark: 56
Pass
Fail
Enter your mark: 56
Pass
Syntax:
if(condition)
statement;
statement;
Program:
import java.util.Scanner;
class result
{
public static void main(String[] args)
{
int mark;
Scanner s=new Scanner(System.in);
System.out.print("Enter your mark: ");
mark=s.nextInt();
if ( mark >= 40 )
{
System.out.println("Pass");
}
}
class result
{
public static void main(String[] args)
{
int mark;
Scanner s=new Scanner(System.in);
System.out.print("Enter your mark: ");
mark=s.nextInt();
if ( mark >= 40 )
{
System.out.println("Pass");
}
}
}
Output:
Enter your mark: 44
Pass
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class palindrome
{
public static void main(String[] args)
{
try
{
System.out.print("Enter a number: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String num=br.readLine();
int no=Integer.parseInt(num);
int temp=no;
int digit=0,ld;
while(no!=0)
{
ld=no%10;
digit=digit*10+ld;
no=no/10;
}
if(temp==digit)
{
System.out.println("Palindrome number");
}
else
{
System.out.println("Not a palindrome number");
}
}
catch (IOException | NumberFormatException ex)
{
}
}
}
import java.io.IOException;
import java.io.InputStreamReader;
class palindrome
{
public static void main(String[] args)
{
try
{
System.out.print("Enter a number: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String num=br.readLine();
int no=Integer.parseInt(num);
int temp=no;
int digit=0,ld;
while(no!=0)
{
ld=no%10;
digit=digit*10+ld;
no=no/10;
}
if(temp==digit)
{
System.out.println("Palindrome number");
}
else
{
System.out.println("Not a palindrome number");
}
}
catch (IOException | NumberFormatException ex)
{
}
}
}
Output:
Enter a number: 123
Not a palindrome number
Not a palindrome number
Enter a number: 12321
Palindrome number
Palindrome number
import java.io.InputStreamReader;
class Reverse
{
public static void main(String[] args)
{
try
{
System.out.print("Enter string : ");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String str=in.readLine();
for(int i=str.length()-1;i>=0;i--)
{
System.out.print(str.charAt(i));
}
}
catch (Exception ex)
{
}
}
}
Output:
Enter string : VIJAY
YAJIV
import java.util.Scanner;
class fibonacci
{
public static void main(String[] args)
{
System.out.print("Enter the number to display fibonicci series: ");
Scanner in=new Scanner(System.in);
int num=in.nextInt();
int a=0,b=1,c=0,i=0;
while(i!=num)
{
System.out.println(c);
a=b;
b=c;
c=a+b;
i++;
}
}
}
class fibonacci
{
public static void main(String[] args)
{
System.out.print("Enter the number to display fibonicci series: ");
Scanner in=new Scanner(System.in);
int num=in.nextInt();
int a=0,b=1,c=0,i=0;
while(i!=num)
{
System.out.println(c);
a=b;
b=c;
c=a+b;
i++;
}
}
}
Output:
import java.util.Scanner;
class pyramidShape
{
public static void main(String[] args)
{
System.out.print("Enter number of rows: ");
Scanner in = new Scanner(System.in);
int num=in.nextInt();
for(int i=1;i<=num;i++)
{
for(int j=num;j>=i;j--)
{
System.out.print(" ");
}
for(int m=1;m<=i*2-1;m++)
{
System.out.print("*");
}
System.out.print("\n");
}
}
}
class pyramidShape
{
public static void main(String[] args)
{
System.out.print("Enter number of rows: ");
Scanner in = new Scanner(System.in);
int num=in.nextInt();
for(int i=1;i<=num;i++)
{
for(int j=num;j>=i;j--)
{
System.out.print(" ");
}
for(int m=1;m<=i*2-1;m++)
{
System.out.print("*");
}
System.out.print("\n");
}
}
}
Output:
import java.util.Scanner;
class diamondShape
{
public static void main(String[] args)
{
System.out.print("Enter number of rows: ");
Scanner in = new Scanner(System.in);
int num=in.nextInt();
for(int i=1;i<=num;i++)
{
for(int j=num;j>=i;j--)
{
System.out.print(" ");
}
for(int m=1;m<=i;m++)
{
System.out.print(" *");
}
System.out.print("\n");
}
for(int i=1;i<=num;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(" ");
}
for(int m=num;m>=i;m--)
{
System.out.print(" *");
}
System.out.print("\n");
}
}
}
class diamondShape
{
public static void main(String[] args)
{
System.out.print("Enter number of rows: ");
Scanner in = new Scanner(System.in);
int num=in.nextInt();
for(int i=1;i<=num;i++)
{
for(int j=num;j>=i;j--)
{
System.out.print(" ");
}
for(int m=1;m<=i;m++)
{
System.out.print(" *");
}
System.out.print("\n");
}
for(int i=1;i<=num;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(" ");
}
for(int m=num;m>=i;m--)
{
System.out.print(" *");
}
System.out.print("\n");
}
}
}
Output:
Client / Server Program With Acknowledgement
Friday, 26 June 2015
Posted by Unknown
Tag :
Client Server Program
Sender Side Program
import java.io.*;
import java.net.*;
class slidingSender
{
public void process()
{
try
{
ServerSocket server= new ServerSocket(2500);
Socket client = server.accept();
BufferedReader user=new BufferedReader(new InputStreamReader(System.in));
BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter pr=new PrintWriter(client.getOutputStream(),true);
String buf[]=new String[8];
int index=0,sws=8,rws;
String ch;
do
{
System.out.println("Enter the number of frame send to the receiver:");
int nf=Integer.parseInt(user.readLine());
pr.println(nf);
if(nf<=sws-1)
{
System.out.println("Enter the "+nf+" Message send to the receiver");
for(int i=0;i<nf;i++)
{
buf[i]=user.readLine();
pr.println(buf[i]);
}
sws=sws-nf;
int ackno=Integer.parseInt(br.readLine());
System.out.println("Acknowledge Received For the Frame"+ackno);
sws=sws+nf;
}
else
{
System.out.println("SENDER WINDOW SIZE EXCEEDS");
}
System.out.println("Do You Want To Continue(y/n)");
ch=user.readLine();
pr.println(ch);
}
while(ch.equals("y"));
}
catch(Exception e){}
}
public static void main(String arg[])
{
slidingSender s= new slidingSender();
s.process();
}
}
import java.net.*;
class slidingSender
{
public void process()
{
try
{
ServerSocket server= new ServerSocket(2500);
Socket client = server.accept();
BufferedReader user=new BufferedReader(new InputStreamReader(System.in));
BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter pr=new PrintWriter(client.getOutputStream(),true);
String buf[]=new String[8];
int index=0,sws=8,rws;
String ch;
do
{
System.out.println("Enter the number of frame send to the receiver:");
int nf=Integer.parseInt(user.readLine());
pr.println(nf);
if(nf<=sws-1)
{
System.out.println("Enter the "+nf+" Message send to the receiver");
for(int i=0;i<nf;i++)
{
buf[i]=user.readLine();
pr.println(buf[i]);
}
sws=sws-nf;
int ackno=Integer.parseInt(br.readLine());
System.out.println("Acknowledge Received For the Frame"+ackno);
sws=sws+nf;
}
else
{
System.out.println("SENDER WINDOW SIZE EXCEEDS");
}
System.out.println("Do You Want To Continue(y/n)");
ch=user.readLine();
pr.println(ch);
}
while(ch.equals("y"));
}
catch(Exception e){}
}
public static void main(String arg[])
{
slidingSender s= new slidingSender();
s.process();
}
}
Receiver Side Program
import java.io.*;
import java.net.*;
class slidingReceiver
{
public void process()
{
try
{
Socket client = new Socket(InetAddress.getLocalHost(),2500);
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader user=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pr=new PrintWriter(client.getOutputStream(),true);
int index=0,rws=8;
String buf[]=new String[8];
String ch;
while(true)
{
do
{
int nf=Integer.parseInt(br.readLine());
if(nf<rws-1)
{
for(int i=0;i<nf;i++)
{
buf[index]=br.readLine();
System.out.println(index);
System.out.println(buf[index]);
index=(index +1)%rws;
System.out.println(index);
}
rws = rws - nf;
System.out.println("Acknowledge Sent To Sender");
pr.println(index);
rws=rws+nf;
}
else
{
break;
}
ch=br.readLine();
}
while(ch.equals("y"));
}
}
catch(Exception e){}
}
public static void main(String arg[])
{
slidingReceiver r= new slidingReceiver();
r.process();
}
}
import java.net.*;
class slidingReceiver
{
public void process()
{
try
{
Socket client = new Socket(InetAddress.getLocalHost(),2500);
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader user=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pr=new PrintWriter(client.getOutputStream(),true);
int index=0,rws=8;
String buf[]=new String[8];
String ch;
while(true)
{
do
{
int nf=Integer.parseInt(br.readLine());
if(nf<rws-1)
{
for(int i=0;i<nf;i++)
{
buf[index]=br.readLine();
System.out.println(index);
System.out.println(buf[index]);
index=(index +1)%rws;
System.out.println(index);
}
rws = rws - nf;
System.out.println("Acknowledge Sent To Sender");
pr.println(index);
rws=rws+nf;
}
else
{
break;
}
ch=br.readLine();
}
while(ch.equals("y"));
}
}
catch(Exception e){}
}
public static void main(String arg[])
{
slidingReceiver r= new slidingReceiver();
r.process();
}
}
How to run:
- First run Sender program
- Then next run Receiver program
- Give input from Sender side
Sender Side Output:
Enter the number of frame send to the receiver:
3
Enter the 3 Message send to the receiver
hi
good
evening
Acknowledge Received For the Frame3
Do You Want To Continue(y/n)
n
3
Enter the 3 Message send to the receiver
hi
good
evening
Acknowledge Received For the Frame3
Do You Want To Continue(y/n)
n
Receiver Side Output:
0
hi
1
1
good
2
2
evening
3
Acknowledge Sent To Sender
Multicast Sender
import java.net.*;
import java.io.*;
class MulticastSender implements Runnable
{
static int port;
static MulticastSocket ms;
static String group;
static int status = 0 ;
MulticastSender() throws Exception
{
port = 5000;
group = "225.4.5.6";
ms = new MulticastSocket(4000);
}
public void run()
{
while(true)
{
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
byte sbuf[] = new byte[2000];
sbuf = br.readLine().getBytes();
DatagramPacket spack = new DatagramPacket(sbuf, sbuf.length,
InetAddress.getByName(group), port);
ms.send(spack);
}catch(Exception e){ System.out.println(e);}
}
}
public static void main(String args[]) throws Exception
{
MulticastSender sender = new MulticastSender();
Thread t = new Thread(sender);
ms.joinGroup(InetAddress.getByName(group));
t.start();
int count =0;
byte rbuf[] = new byte[1000];
while(true)
{
DatagramPacket rpack =new DatagramPacket(rbuf,rbuf.length);
ms.receive(rpack);
String str = new String(rpack.getData(),0,rpack.getLength());
if(str.equalsIgnoreCase("join"))
{
count++;
System.out.println("Client joined the group");
System.out.println("\ncurrently " + count + " client/clients is/are in the group");
}
else if(str.equalsIgnoreCase("leave"))
{
count--;
System.out.println("Client left the group");
System.out.println("\ncurrently " + count + " client/clients is/are in the group");
if(count == 0)
{
ms.leaveGroup(InetAddress.getByName(group));
ms.close();
break;
}
}
}
}
}
import java.io.*;
class MulticastSender implements Runnable
{
static int port;
static MulticastSocket ms;
static String group;
static int status = 0 ;
MulticastSender() throws Exception
{
port = 5000;
group = "225.4.5.6";
ms = new MulticastSocket(4000);
}
public void run()
{
while(true)
{
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
byte sbuf[] = new byte[2000];
sbuf = br.readLine().getBytes();
DatagramPacket spack = new DatagramPacket(sbuf, sbuf.length,
InetAddress.getByName(group), port);
ms.send(spack);
}catch(Exception e){ System.out.println(e);}
}
}
public static void main(String args[]) throws Exception
{
MulticastSender sender = new MulticastSender();
Thread t = new Thread(sender);
ms.joinGroup(InetAddress.getByName(group));
t.start();
int count =0;
byte rbuf[] = new byte[1000];
while(true)
{
DatagramPacket rpack =new DatagramPacket(rbuf,rbuf.length);
ms.receive(rpack);
String str = new String(rpack.getData(),0,rpack.getLength());
if(str.equalsIgnoreCase("join"))
{
count++;
System.out.println("Client joined the group");
System.out.println("\ncurrently " + count + " client/clients is/are in the group");
}
else if(str.equalsIgnoreCase("leave"))
{
count--;
System.out.println("Client left the group");
System.out.println("\ncurrently " + count + " client/clients is/are in the group");
if(count == 0)
{
ms.leaveGroup(InetAddress.getByName(group));
ms.close();
break;
}
}
}
}
}
Multicast Receiver
import java.io.*;
import java.net.*;
class MulticastReceiver implements Runnable
{
static MulticastSocket ms;
static int port;
static int status = 0;
MulticastReceiver() throws Exception
{
port = 5000;
ms= new MulticastSocket(port);
}
public void run()
{
while(true)
{
try
{
byte rbuf[] = new byte[2000];
DatagramPacket rpack = new DatagramPacket(rbuf,rbuf.length);
if (status == 1)
{
ms.close();
break;
}
ms.receive(rpack);
System.out.println(new String(rpack.getData(),0,rpack.getLength()));
}catch(Exception e){System.out.println(e);}
}
}
public static void main(String args[]) throws Exception
{
MulticastReceiver mr =new MulticastReceiver();
Thread t = new Thread(mr);
String group = "225.4.5.6";
System.out.println("Do you wish to join the group?");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
if(br.readLine().equalsIgnoreCase("yes"))
{
ms.joinGroup(InetAddress.getByName(group));
byte sbuf[] = new byte[2000];
sbuf = "join".getBytes();
DatagramPacket spack = new DatagramPacket(sbuf, sbuf.length,InetAddress.getByName("localhost"),4000);
ms.send(spack);
System.out.println("Joined the group");
t.start();
while(true)
{
if(br.readLine().equalsIgnoreCase("leave"))
{
status = 1;
byte sbuf2[] = new byte[2000];
sbuf2 = "leave".getBytes();
DatagramPacket spack2 = new DatagramPacket(sbuf2,sbuf2.length,InetAddress.getByName("localhost"),4000);
ms.send(spack2);
ms.leaveGroup(InetAddress.getByName(group));
break;
}
}
}
}
}
import java.net.*;
class MulticastReceiver implements Runnable
{
static MulticastSocket ms;
static int port;
static int status = 0;
MulticastReceiver() throws Exception
{
port = 5000;
ms= new MulticastSocket(port);
}
public void run()
{
while(true)
{
try
{
byte rbuf[] = new byte[2000];
DatagramPacket rpack = new DatagramPacket(rbuf,rbuf.length);
if (status == 1)
{
ms.close();
break;
}
ms.receive(rpack);
System.out.println(new String(rpack.getData(),0,rpack.getLength()));
}catch(Exception e){System.out.println(e);}
}
}
public static void main(String args[]) throws Exception
{
MulticastReceiver mr =new MulticastReceiver();
Thread t = new Thread(mr);
String group = "225.4.5.6";
System.out.println("Do you wish to join the group?");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
if(br.readLine().equalsIgnoreCase("yes"))
{
ms.joinGroup(InetAddress.getByName(group));
byte sbuf[] = new byte[2000];
sbuf = "join".getBytes();
DatagramPacket spack = new DatagramPacket(sbuf, sbuf.length,InetAddress.getByName("localhost"),4000);
ms.send(spack);
System.out.println("Joined the group");
t.start();
while(true)
{
if(br.readLine().equalsIgnoreCase("leave"))
{
status = 1;
byte sbuf2[] = new byte[2000];
sbuf2 = "leave".getBytes();
DatagramPacket spack2 = new DatagramPacket(sbuf2,sbuf2.length,InetAddress.getByName("localhost"),4000);
ms.send(spack2);
ms.leaveGroup(InetAddress.getByName(group));
break;
}
}
}
}
}
How to run:
- First run Receiver program
- Then next run Sender program in single or multiple times
- Give input "yes" from Receiver side
- Next give input in Sender side
Receiver Side Output:
Do you wish to join the group?
yes
Joined the group
hi
yes
Joined the group
hi
Sender Side Output:
Client joined the group
currently 1 client/clients is/are in the group
hi
currently 1 client/clients is/are in the group
hi
import java.io.*;
class ShortPath
{
public int vertex;
public int edge;
public int arrval[][]=new int[10][10];
public int neigh[]=new int[10];
public int nonnei[]=new int[10];
public int tempnei,ntnei;
public void getdata() throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("ENTER NO OF VERTEX==>");
vertex=Integer.parseInt(br.readLine());
System.out.println("ENTER NO OF EDGE==>");
edge=Integer.parseInt(br.readLine());
for(int i=0;i<vertex;i++)
{
for(int j=0;j<vertex;j++)
{
if(i==j)
arrval[i][j]=0;
else
arrval[i][j]=999;
}
}
for(int k=0;k<edge;k++)
{
System.out.println("ENTER THE EDGE V1-V2");
int v1=Integer.parseInt(br.readLine());
int v2=Integer.parseInt(br.readLine());
System.out.println("ENTER THE EDGE COST==>");
int cost=Integer.parseInt(br.readLine());
arrval[v1][v2]=cost;
arrval[v2][v1]=cost;
}
}
public void process()throws Exception
{
int i,j,k;
for(i=0;i<vertex;i++)
{
tempnei=0;
ntnei=0;
for(j=0;j<vertex;j++)
{
if(arrval[i][j]!=0 && arrval[i][j]!=999)
tempnei++;
else
ntnei++;
}
neigh[i]=tempnei;
nonnei[i]=ntnei;
}
for(k=0;k<vertex;k++)
{
System.out.println("THE NUMBER OF NEIGHBOUR VERTEX==>"+neigh[k]);
System.out.println("THE NUMBER OF NON-NEIGHBOUR VERTEX==>"+nonnei[k]);
}
for(k=0;k<vertex;k++)
{
for(i=0;i<vertex;i++)
{
for(j=0;j<vertex;j++)
{
arrval[i][j]=min(arrval[i][j],arrval[i][k]+arrval[k][j]);
}
}
}
}
public void display()throws Exception
{
System.out.println("SHORTEST PATH");
System.out.println();
for(int i=0;i<vertex;i++)
{
for(int j=0;j<vertex;j++)
{
System.out.print(arrval[i][j]+"\t");
}
System.out.println();
}
}
public int min(int a,int b)
{
int c=a<b?a:b;
return c;
}
public static void main(String arg[])throws Exception
{
ShortPath s=new ShortPath();
s.getdata();
s.display();
s.process();
s.display();
}
}
class ShortPath
{
public int vertex;
public int edge;
public int arrval[][]=new int[10][10];
public int neigh[]=new int[10];
public int nonnei[]=new int[10];
public int tempnei,ntnei;
public void getdata() throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("ENTER NO OF VERTEX==>");
vertex=Integer.parseInt(br.readLine());
System.out.println("ENTER NO OF EDGE==>");
edge=Integer.parseInt(br.readLine());
for(int i=0;i<vertex;i++)
{
for(int j=0;j<vertex;j++)
{
if(i==j)
arrval[i][j]=0;
else
arrval[i][j]=999;
}
}
for(int k=0;k<edge;k++)
{
System.out.println("ENTER THE EDGE V1-V2");
int v1=Integer.parseInt(br.readLine());
int v2=Integer.parseInt(br.readLine());
System.out.println("ENTER THE EDGE COST==>");
int cost=Integer.parseInt(br.readLine());
arrval[v1][v2]=cost;
arrval[v2][v1]=cost;
}
}
public void process()throws Exception
{
int i,j,k;
for(i=0;i<vertex;i++)
{
tempnei=0;
ntnei=0;
for(j=0;j<vertex;j++)
{
if(arrval[i][j]!=0 && arrval[i][j]!=999)
tempnei++;
else
ntnei++;
}
neigh[i]=tempnei;
nonnei[i]=ntnei;
}
for(k=0;k<vertex;k++)
{
System.out.println("THE NUMBER OF NEIGHBOUR VERTEX==>"+neigh[k]);
System.out.println("THE NUMBER OF NON-NEIGHBOUR VERTEX==>"+nonnei[k]);
}
for(k=0;k<vertex;k++)
{
for(i=0;i<vertex;i++)
{
for(j=0;j<vertex;j++)
{
arrval[i][j]=min(arrval[i][j],arrval[i][k]+arrval[k][j]);
}
}
}
}
public void display()throws Exception
{
System.out.println("SHORTEST PATH");
System.out.println();
for(int i=0;i<vertex;i++)
{
for(int j=0;j<vertex;j++)
{
System.out.print(arrval[i][j]+"\t");
}
System.out.println();
}
}
public int min(int a,int b)
{
int c=a<b?a:b;
return c;
}
public static void main(String arg[])throws Exception
{
ShortPath s=new ShortPath();
s.getdata();
s.display();
s.process();
s.display();
}
}
Output:
ENTER NO OF VERTEX==>
2
ENTER NO OF EDGE==>
2
ENTER THE EDGE V1-V2
2
3
ENTER THE EDGE COST==>
5
ENTER THE EDGE V1-V2
2
3
ENTER THE EDGE COST==>
6
SHORTEST PATH
0 999
999 0
THE NUMBER OF NEIGHBOUR VERTEX==>0
THE NUMBER OF NON-NEIGHBOUR VERTEX==>2
THE NUMBER OF NEIGHBOUR VERTEX==>0
THE NUMBER OF NON-NEIGHBOUR VERTEX==>2
SHORTEST PATH
0 999
999 0
Client Side Program
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String args[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("127.0.0.1", 6324);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
import java.net.*;
class TCPClient {
public static void main(String args[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("127.0.0.1", 6324);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
Server Side Program
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String args[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6324);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("FROM client:" + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
}
import java.net.*;
class TCPServer {
public static void main(String args[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6324);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("FROM client:" + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
}
How to run:
- First run server program then next run client program
- Give input from client side
- Next give input in server side
Client Side Output:
hi
FROM SERVER: HI
Server Side Output:
FROM client:hi
hi da
Client Side Program
import java.io.*;
import java.net.*;
class ChatClient extends Thread
{
Socket s;
static PrintWriter out;
static BufferedReader read,in;
Thread t;
ChatClient() throws Exception
{
s = new Socket("127.0.0.1",5000);
System.out.println("client connected to server");
read = new BufferedReader(new InputStreamReader(System.in));
in=new BufferedReader(new InputStreamReader(s.getInputStream()));
out=new PrintWriter(s.getOutputStream());
t=new Thread(this);
t.start();
}
public void run()
{
String str1;
while(true)
{
try
{
str1=in.readLine();
System.out.println("\n"+"From server: "+str1);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public static void main(String args[]) throws Exception
{
String str2;
new ChatClient();
while(true)
{
str2=read.readLine();
out.println(str2);
out.flush();
}
}
}
Server Side Program
import java.io.*;
import java.net.*;
class ChatServerTCP extends Thread
{
ServerSocket server;
Socket s;
static PrintWriter out;
static BufferedReader read,in;
Thread t;
ChatServerTCP() throws Exception
{
server = new ServerSocket(5000);
System.out.println("Server is waiting for client");
s=server.accept();
System.out.println("connection is established "+s.getInetAddress());
read = new BufferedReader(new InputStreamReader(System.in));
in=new BufferedReader(new InputStreamReader(s.getInputStream()));
out=new PrintWriter(s.getOutputStream());
t=new Thread(this);
t.start();
}
public void run()
{
String str1;
while(true)
{
try
{
str1=in.readLine();
System.out.println("\n"+"From client: "+str1);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public static void main(String args[]) throws Exception
{
ChatServerTCP cs = new ChatServerTCP();
String str2;
while(true)
{
str2=read.readLine();
out.println(str2);
out.flush();
}
}
}
import java.net.*;
class ChatServerTCP extends Thread
{
ServerSocket server;
Socket s;
static PrintWriter out;
static BufferedReader read,in;
Thread t;
ChatServerTCP() throws Exception
{
server = new ServerSocket(5000);
System.out.println("Server is waiting for client");
s=server.accept();
System.out.println("connection is established "+s.getInetAddress());
read = new BufferedReader(new InputStreamReader(System.in));
in=new BufferedReader(new InputStreamReader(s.getInputStream()));
out=new PrintWriter(s.getOutputStream());
t=new Thread(this);
t.start();
}
public void run()
{
String str1;
while(true)
{
try
{
str1=in.readLine();
System.out.println("\n"+"From client: "+str1);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public static void main(String args[]) throws Exception
{
ChatServerTCP cs = new ChatServerTCP();
String str2;
while(true)
{
str2=read.readLine();
out.println(str2);
out.flush();
}
}
}
How to run:
- First run server program then next run client program
- Give input from client side
- Next give input in server side
Client Side Output:
client connected to server
hi
From server: hi da
how r u?
From server: fine
hi
From server: hi da
how r u?
From server: fine
Server Side Output:
Server is waiting for client
connection is established /127.0.0.1
From client: hi
hi da
From client:
From client: how r u?
fine
import java.util.Scanner;
class solutions
{
public static void main(String[] args)
{
int a,b,c;
double x,y;
Scanner s=new Scanner(System.in);
System.out.println("Enter the values of a, b, c:");
a=s.nextInt();
b=s.nextInt();
c=s.nextInt();
int k=(b*b)-4*a*c;
if(k<0)
{
System.out.println("No real roots");
}
else
{
double l=Math.sqrt(k);
x=(-b-l)/2*a;
y=(-b+l)/2*a;
System.out.println("Roots of given equation:"+x+"
"+y);
}
}
}
Output:
Enter the values of a, b, c:
5
5
2
No real roots
5
5
2
No real roots
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class TransparencyDemo extends JPanel
import javax.swing.*;
import javax.swing.event.*;
public class TransparencyDemo extends JPanel
{
public static void main(String[] args)
public static void main(String[] args)
{
JFrame window = new JFrame("TransparencyDemo");
TransparencyDemo content = new TransparencyDemo();
window.setContentPane(content);
window.pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation( (screenSize.width - window.getWidth())/2,
(screenSize.height - window.getHeight())/2 );
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setVisible(true);
}
private JSlider triangleTransparency;
private JSlider ovalTransparency;
private JSlider rectangleTransparency;
private JSlider textTransparency;
private Font textFont = new Font("Serif",Font.BOLD,42);
private JPanel display = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Color triangleColor = new Color(255,0,0,triangleTransparency.getValue());
Color ovalColor = new Color(0,255,0,ovalTransparency.getValue());
Color rectangleColor = new Color(0,0,255,rectangleTransparency.getValue());
Color textColor = new Color(0,0,0,textTransparency.getValue());
g.setColor(triangleColor);
g.fillPolygon(new int[] { scaleX(0.25), scaleX(0.7), scaleX(0.1) },
new int[] { scaleY(0.1), scaleY(0.7), scaleY(0.7) },
3);
g.setColor(ovalColor);
g.fillOval(scaleX(0.3),scaleY(0.45),getWidth()/2,getHeight()/2);
g.setColor(rectangleColor);
g.fillRect(scaleX(0.4),scaleY(0.15),getWidth()/2,getHeight()/2);
FontMetrics metrics = g.getFontMetrics(textFont);
int lineWidth1 = metrics.stringWidth("Transparency");
int lineWidth2 = metrics.stringWidth("Demo");
int textHeight = metrics.getHeight() + metrics.getAscent();
int topSkip = (getHeight() - textHeight) / 2;
int leftSkip1 = (getWidth() - lineWidth1) / 2;
int leftSkip2 = (getWidth() - lineWidth2) / 2;
g.setColor(textColor);
g.setFont(textFont);
g.drawString("Transparency", leftSkip1, topSkip + metrics.getAscent());
g.drawString("Demo", leftSkip2, topSkip + metrics.getAscent() + metrics.getHeight());
}
private int scaleX(double x) {
return (int)(x * getWidth());
}
private int scaleY(double y) {
return (int)(y * getHeight());
}
};
private ChangeListener listener = new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
display.repaint();
}
};
public TransparencyDemo() {
setLayout(new BorderLayout(3,3));
setBorder(BorderFactory.createLineBorder(Color.GRAY,2));
setBackground(Color.GRAY);
display.setBackground(Color.WHITE);
display.setPreferredSize(new Dimension(400,300));
add(display,BorderLayout.CENTER);
JPanel bottom = new JPanel();
bottom.setLayout(new GridLayout(4,2,3,3));
add(bottom,BorderLayout.SOUTH);
bottom.add( new JLabel(" Triangle Transparency:") );
triangleTransparency = new JSlider(0,255);
triangleTransparency.addChangeListener(listener);
bottom.add( triangleTransparency );
bottom.add( new JLabel(" Oval Transparency:") );
ovalTransparency = new JSlider(0,255);
ovalTransparency.addChangeListener(listener);
bottom.add( ovalTransparency );
bottom.add( new JLabel(" Rectangle Transparency:") );
rectangleTransparency = new JSlider(0,255);
rectangleTransparency.addChangeListener(listener);
bottom.add( rectangleTransparency );
bottom.add( new JLabel(" Text Transparency:") );
textTransparency = new JSlider(0,255);
textTransparency.addChangeListener(listener);
bottom.add( textTransparency );
}
}
JFrame window = new JFrame("TransparencyDemo");
TransparencyDemo content = new TransparencyDemo();
window.setContentPane(content);
window.pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation( (screenSize.width - window.getWidth())/2,
(screenSize.height - window.getHeight())/2 );
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setVisible(true);
}
private JSlider triangleTransparency;
private JSlider ovalTransparency;
private JSlider rectangleTransparency;
private JSlider textTransparency;
private Font textFont = new Font("Serif",Font.BOLD,42);
private JPanel display = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Color triangleColor = new Color(255,0,0,triangleTransparency.getValue());
Color ovalColor = new Color(0,255,0,ovalTransparency.getValue());
Color rectangleColor = new Color(0,0,255,rectangleTransparency.getValue());
Color textColor = new Color(0,0,0,textTransparency.getValue());
g.setColor(triangleColor);
g.fillPolygon(new int[] { scaleX(0.25), scaleX(0.7), scaleX(0.1) },
new int[] { scaleY(0.1), scaleY(0.7), scaleY(0.7) },
3);
g.setColor(ovalColor);
g.fillOval(scaleX(0.3),scaleY(0.45),getWidth()/2,getHeight()/2);
g.setColor(rectangleColor);
g.fillRect(scaleX(0.4),scaleY(0.15),getWidth()/2,getHeight()/2);
FontMetrics metrics = g.getFontMetrics(textFont);
int lineWidth1 = metrics.stringWidth("Transparency");
int lineWidth2 = metrics.stringWidth("Demo");
int textHeight = metrics.getHeight() + metrics.getAscent();
int topSkip = (getHeight() - textHeight) / 2;
int leftSkip1 = (getWidth() - lineWidth1) / 2;
int leftSkip2 = (getWidth() - lineWidth2) / 2;
g.setColor(textColor);
g.setFont(textFont);
g.drawString("Transparency", leftSkip1, topSkip + metrics.getAscent());
g.drawString("Demo", leftSkip2, topSkip + metrics.getAscent() + metrics.getHeight());
}
private int scaleX(double x) {
return (int)(x * getWidth());
}
private int scaleY(double y) {
return (int)(y * getHeight());
}
};
private ChangeListener listener = new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
display.repaint();
}
};
public TransparencyDemo() {
setLayout(new BorderLayout(3,3));
setBorder(BorderFactory.createLineBorder(Color.GRAY,2));
setBackground(Color.GRAY);
display.setBackground(Color.WHITE);
display.setPreferredSize(new Dimension(400,300));
add(display,BorderLayout.CENTER);
JPanel bottom = new JPanel();
bottom.setLayout(new GridLayout(4,2,3,3));
add(bottom,BorderLayout.SOUTH);
bottom.add( new JLabel(" Triangle Transparency:") );
triangleTransparency = new JSlider(0,255);
triangleTransparency.addChangeListener(listener);
bottom.add( triangleTransparency );
bottom.add( new JLabel(" Oval Transparency:") );
ovalTransparency = new JSlider(0,255);
ovalTransparency.addChangeListener(listener);
bottom.add( ovalTransparency );
bottom.add( new JLabel(" Rectangle Transparency:") );
rectangleTransparency = new JSlider(0,255);
rectangleTransparency.addChangeListener(listener);
bottom.add( rectangleTransparency );
bottom.add( new JLabel(" Text Transparency:") );
textTransparency = new JSlider(0,255);
textTransparency.addChangeListener(listener);
bottom.add( textTransparency );
}
}
Output:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class ToolBarDemo extends JPanel
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class ToolBarDemo extends JPanel
{
public static void main(String[] args)
public static void main(String[] args)
{
JFrame window = new JFrame("ToolBarDemo");
ToolBarDemo content = new ToolBarDemo();
window.setContentPane(content);
window.pack();
window.setResizable(false);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation( (screenSize.width - window.getWidth())/2,
(screenSize.height - window.getHeight())/2 );
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setVisible(true);
}
private class Display extends JPanel implements MouseListener, MouseMotionListener
JFrame window = new JFrame("ToolBarDemo");
ToolBarDemo content = new ToolBarDemo();
window.setContentPane(content);
window.pack();
window.setResizable(false);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation( (screenSize.width - window.getWidth())/2,
(screenSize.height - window.getHeight())/2 );
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setVisible(true);
}
private class Display extends JPanel implements MouseListener, MouseMotionListener
{
private BufferedImage OSC; // Off-screen canvas.
private Color currentColor = Color.RED; // Current drawing color.
private int prevX, prevY; // Previous mouse position, during mouse drags.
private BasicStroke stroke; // Stroke used for drawing.
Display() { // constructor.
addMouseListener(this);
addMouseMotionListener(this);
setPreferredSize(new Dimension(300,300));
stroke = new BasicStroke(3,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
}
void setCurrentColor(Color c) { // change current drawing color
currentColor = c;
}
void clear() { // clear the drawing area by filling it with white
if (OSC != null) {
Graphics g = OSC.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0,0,getWidth(),getHeight());
g.dispose();
repaint();
}
}
public void paintComponent(Graphics g) { // just copies OSC to screen
checkImage();
g.drawImage(OSC,0,0,null);
}
void checkImage() { // create or resize OSC if necessary
if (OSC == null) {
// Create the OSC, with a size to match the size of the panel.
OSC = new BufferedImage(getWidth(),getHeight(),BufferedImage.TYPE_INT_RGB);
clear();
}
else if (OSC.getWidth() != getWidth() || OSC.getHeight() != getHeight()) {
BufferedImage newOSC;
newOSC = new BufferedImage(getWidth(),getHeight(),BufferedImage.TYPE_INT_RGB);
Graphics g = newOSC.getGraphics();
g.drawImage(OSC,0,0,getWidth(),getHeight(),null);
g.dispose();
OSC = newOSC;
}
}
public void mousePressed(MouseEvent e) {
prevX = e.getX();
prevY = e.getY();
}
public void mouseDragged(MouseEvent e) {
Graphics2D g2 = (Graphics2D)OSC.getGraphics();
g2.setColor(currentColor);
g2.setStroke(stroke);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.drawLine(prevX,prevY,e.getX(),e.getY());
g2.dispose();
repaint();
prevX = e.getX();
prevY = e.getY();
}
public void mouseReleased(MouseEvent e) { }
public void mouseMoved(MouseEvent e) { }
public void mouseClicked(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
}
private Display display;
private BufferedImage OSC; // Off-screen canvas.
private Color currentColor = Color.RED; // Current drawing color.
private int prevX, prevY; // Previous mouse position, during mouse drags.
private BasicStroke stroke; // Stroke used for drawing.
Display() { // constructor.
addMouseListener(this);
addMouseMotionListener(this);
setPreferredSize(new Dimension(300,300));
stroke = new BasicStroke(3,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
}
void setCurrentColor(Color c) { // change current drawing color
currentColor = c;
}
void clear() { // clear the drawing area by filling it with white
if (OSC != null) {
Graphics g = OSC.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0,0,getWidth(),getHeight());
g.dispose();
repaint();
}
}
public void paintComponent(Graphics g) { // just copies OSC to screen
checkImage();
g.drawImage(OSC,0,0,null);
}
void checkImage() { // create or resize OSC if necessary
if (OSC == null) {
// Create the OSC, with a size to match the size of the panel.
OSC = new BufferedImage(getWidth(),getHeight(),BufferedImage.TYPE_INT_RGB);
clear();
}
else if (OSC.getWidth() != getWidth() || OSC.getHeight() != getHeight()) {
BufferedImage newOSC;
newOSC = new BufferedImage(getWidth(),getHeight(),BufferedImage.TYPE_INT_RGB);
Graphics g = newOSC.getGraphics();
g.drawImage(OSC,0,0,getWidth(),getHeight(),null);
g.dispose();
OSC = newOSC;
}
}
public void mousePressed(MouseEvent e) {
prevX = e.getX();
prevY = e.getY();
}
public void mouseDragged(MouseEvent e) {
Graphics2D g2 = (Graphics2D)OSC.getGraphics();
g2.setColor(currentColor);
g2.setStroke(stroke);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.drawLine(prevX,prevY,e.getX(),e.getY());
g2.dispose();
repaint();
prevX = e.getX();
prevY = e.getY();
}
public void mouseReleased(MouseEvent e) { }
public void mouseMoved(MouseEvent e) { }
public void mouseClicked(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
}
private Display display;
public ToolBarDemo() {
setLayout(new BorderLayout(2,2));
setBackground(Color.GRAY);
setBorder(BorderFactory.createLineBorder(Color.GRAY,2));
display = new Display();
add(display, BorderLayout.CENTER);
JToolBar toolbar = new JToolBar();
add(toolbar, BorderLayout.NORTH);
ButtonGroup group = new ButtonGroup();
toolbar.add( makeColorRadioButton(Color.RED,group,true) );
toolbar.add( makeColorRadioButton(Color.GREEN,group,false) );
toolbar.add( makeColorRadioButton(Color.BLUE,group,false) );
toolbar.addSeparator(new Dimension(20,20));
toolbar.add( makeClearButton() );
}
private JRadioButton makeColorRadioButton(final Color c, ButtonGroup grp, boolean selected) {
BufferedImage image = new BufferedImage(30,30,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0,0,30,30);
g.setColor(c);
g.fill3DRect(1, 1, 24, 24, true);
g.dispose();
Icon unselectedIcon = new ImageIcon(image);
/* Create an ImageIcon for the selected state of the button. */
image = new BufferedImage(30,30,BufferedImage.TYPE_INT_RGB);
g = image.getGraphics();
g.setColor(Color.DARK_GRAY);
g.fillRect(0,0,30,30);
g.setColor(c);
g.fill3DRect(3, 3, 24, 24, false);
g.dispose();
Icon selectedIcon = new ImageIcon(image);
/* Create and configure the button. */
JRadioButton button = new JRadioButton(unselectedIcon);
button.setSelectedIcon(selectedIcon);
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
// The action for this button sets the current drawing color
// in the display to c.
display.setCurrentColor(c);
}
});
grp.add(button);
if (selected)
button.setSelected(true);
return button;
} // end makeColorRadioButton
private JButton makeClearButton() {
BufferedImage image = new BufferedImage(24,24,BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D)image.getGraphics();
g2.setColor(Color.LIGHT_GRAY);
g2.fillRect(0,0,24,24);
g2.setStroke( new BasicStroke(3));
g2.setColor(Color.BLACK);
g2.drawLine(4,4,20,20);
g2.drawLine(4,20,20,4);
g2.dispose();
Icon clearIcon = new ImageIcon(image);
Action clearAction = new AbstractAction(null,clearIcon) {
public void actionPerformed(ActionEvent evt) {
display.clear();
}
};
clearAction.putValue(Action.SHORT_DESCRIPTION, "Clear the Display");
JButton button = new JButton(clearAction);
return button;
}
}
setLayout(new BorderLayout(2,2));
setBackground(Color.GRAY);
setBorder(BorderFactory.createLineBorder(Color.GRAY,2));
display = new Display();
add(display, BorderLayout.CENTER);
JToolBar toolbar = new JToolBar();
add(toolbar, BorderLayout.NORTH);
ButtonGroup group = new ButtonGroup();
toolbar.add( makeColorRadioButton(Color.RED,group,true) );
toolbar.add( makeColorRadioButton(Color.GREEN,group,false) );
toolbar.add( makeColorRadioButton(Color.BLUE,group,false) );
toolbar.addSeparator(new Dimension(20,20));
toolbar.add( makeClearButton() );
}
private JRadioButton makeColorRadioButton(final Color c, ButtonGroup grp, boolean selected) {
BufferedImage image = new BufferedImage(30,30,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0,0,30,30);
g.setColor(c);
g.fill3DRect(1, 1, 24, 24, true);
g.dispose();
Icon unselectedIcon = new ImageIcon(image);
/* Create an ImageIcon for the selected state of the button. */
image = new BufferedImage(30,30,BufferedImage.TYPE_INT_RGB);
g = image.getGraphics();
g.setColor(Color.DARK_GRAY);
g.fillRect(0,0,30,30);
g.setColor(c);
g.fill3DRect(3, 3, 24, 24, false);
g.dispose();
Icon selectedIcon = new ImageIcon(image);
/* Create and configure the button. */
JRadioButton button = new JRadioButton(unselectedIcon);
button.setSelectedIcon(selectedIcon);
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
// The action for this button sets the current drawing color
// in the display to c.
display.setCurrentColor(c);
}
});
grp.add(button);
if (selected)
button.setSelected(true);
return button;
} // end makeColorRadioButton
private JButton makeClearButton() {
BufferedImage image = new BufferedImage(24,24,BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D)image.getGraphics();
g2.setColor(Color.LIGHT_GRAY);
g2.fillRect(0,0,24,24);
g2.setStroke( new BasicStroke(3));
g2.setColor(Color.BLACK);
g2.drawLine(4,4,20,20);
g2.drawLine(4,20,20,4);
g2.dispose();
Icon clearIcon = new ImageIcon(image);
Action clearAction = new AbstractAction(null,clearIcon) {
public void actionPerformed(ActionEvent evt) {
display.clear();
}
};
clearAction.putValue(Action.SHORT_DESCRIPTION, "Clear the Display");
JButton button = new JButton(clearAction);
return button;
}
}