Multicast Client / Server Program
Friday, 26 June 2015
Posted by Unknown
Tag :
Client Server Program
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;
}
}







