You are on page 1of 14

http://www.gtustudymaterial.

in/
Create a simple TCP chat application where client and server can chat
with each other.

/*
clientServerChatApplicationClientSideProgramming.java
*/

import java.io.*;
import java.net.*;
class clientServerChatApplicationClientSideProgramming
{
public static void main(String args[ ])
throws Exception
{
Socket s = new Socket("localhost", 888);
DataOutputStream dos = new
DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(s.getInputStream()));
BufferedReader kb = new BufferedReader(new
InputStreamReader(System.in));
String str,str1;
while(!(str = kb.readLine()).equals("stop"))
{
dos.writeBytes(str+"\n");
str1 = br.readLine();
System.out.println(str1);
}
dos.close();
br.close();
kb.close();
s.close();
}
}

/*
clientServerChatApplicationServerSideProgramming.java.java
*/

import java.io.*;
import java.net.*;
class clientServerChatApplicationServerSideProgramming.java
{
public static void main(String args[ ])
throws Exception
http://www.gtustudymaterial.in/
{
ServerSocket ss = new ServerSocket(888);
Socket s = ss.accept();
System.out.println("Success!! Connection Established!!");
PrintStream ps = new PrintStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(s.getInputStream()));
BufferedReader kb = new BufferedReader(new
InputStreamReader(System.in));
while(true)
{
String str,str1;
while((str = br.readLine()) != null)
{
System.out.println(str);
str1 = kb.readLine();
ps.println(str1);
}
ps.close();
br.close();
kb.close();
ss.close();
s.close();
System.exit(0);
}
}
}
Create login form which contains a userid, password field, and two
buttons, Submit and Reset. If the userid or password field is left
blank, then on click of submit button, show a message to the user to
fill in the fields. On click of reset button, clear the fields.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Login extends JFrame implements ActionListener
{
JButton SUBMIT,RESET;
JPanel panel;
JLabel label1,label2;
final JTextField text1,text2;
Login()
{
label1 = new JLabel();
label1.setText("Username:");
http://www.gtustudymaterial.in/
text1 = new JTextField(15);
label2 = new JLabel();
label2.setText("Password:");
text2 = new JPasswordField(15);
SUBMIT=new JButton("SUBMIT");
RESET=new JButton("RESET");
panel=new JPanel(new GridLayout(3,1));
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(SUBMIT);
panel.add(RESET);
add(panel,BorderLayout.CENTER);
SUBMIT.addActionListener(this);
RESET.addActionListener(this);
setTitle("LOGIN FORM by KAUSHAL");
}
public void actionPerformed(ActionEvent ae)
{
JButton b = (JButton) ae.getSource();
if (b == SUBMIT)
{
String value1=text1.getText();
String value2=text2.getText();
if (value1.equals("") || value2.equals(""))
{
JOptionPane.showMessageDialog(this,"username and password
must not blank",
"Error",JOptionPane.ERROR_MESSAGE);}
else
{
JOptionPane.showMessageDialog(this,"welcome"+" "+value1);
}
}
else
{
text1.setText("");
text2.setText("");
}
}
}
class pract3
{
public static void main(String arg[])
{
http://www.gtustudymaterial.in/
try
{
Login frame=new Login();
frame.setSize(300,100);
frame.setVisible(true);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e.getMessage());}
}
}
Create a client/server application where the client requests for a
particular file on the server. If the file exists on the server, then write
the contents of the file to the client.

/*
clientServerApplicationFileRetriveServerSideProgramming.java
*/

import java.io.*;
import java.net.*;
class clientServerApplicationFileRetriveServerSideProgramming
{
public static void main(String args[]) throws Exception
{
ServerSocket ss = new ServerSocket(8888);
Socket s = ss.accept();
System.out.println("Success!! Connection Established!!");
BufferedReader cbf = new BufferedReader(new
InputStreamReader(s.getInputStream()));
String FileName = cbf.readLine();
DataOutputStream dos = new
DataOutputStream(s.getOutputStream());
FileReader fr = null;
BufferedReader filebr = null;
File fileNew = new File(FileName);
if(fileNew.exists())
{
dos.writeBytes("Find"+"\n");
fr = new FileReader(FileName);
filebr = new BufferedReader(fr);
String str;
while( (str = filebr.readLine()) != null)
{
http://www.gtustudymaterial.in/
dos.writeBytes(str+"\n");
}
filebr.close();
dos.close();
cbf.close();
fr.close();
s.close();
ss.close();
}
else
{
dos.writeBytes("Oops!! File Not Found!!"+"\n");
}
}
}

/*
clientServerApplicationFileRetriveClientSideProgramming.java
*/

import java.io.*;
import java.net.*;
class clientServerApplicationFileRetriveClientSideProgramming
{
public static void main(String args[]) throws Exception
{
Socket s = new Socket("localhost",8888);
BufferedReader cbf = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter Filename : ");
String FileName = cbf.readLine();
DataOutputStream dos = new
DataOutputStream(s.getOutputStream());
dos.writeBytes(FileName+"\n");
BufferedReader sbf = new BufferedReader(new
InputStreamReader(s.getInputStream()));
String str;
str = sbf.readLine();
if(str.equals("Find"))
{
while((str = sbf.readLine()) != null)
{
System.out.println(str);
}
cbf.close();
dos.close();
http://www.gtustudymaterial.in/
sbf.close();
s.close();
}
}
}
Write an AWT program to create checkboxes for different courses
belongs to a university such that the courses selected would be
displayed.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.*;
/*
<applet code="pract1" width=200 height=200>
</applet>
*/
public class pract1 extends Applet implements ItemListener,ActionListener
{
Button b1;
Checkbox IT = null;
Checkbox CE = null;
Checkbox mech = null;
Checkbox EE = null;
Checkbox EC = null;
Checkbox civil = null;
public void init()
{
//create checkboxes
IT = new Checkbox("IT");
CE = new Checkbox("CE");
mech = new Checkbox("mech");
EE = new Checkbox("EE");
EC = new Checkbox("EC");
civil = new Checkbox("Civil");
b1 = new Button("Output");
add(IT);
add(CE);
add(mech);
add(EE);
add(EC);
add(civil);
add(b1);
//add item listeners
http://www.gtustudymaterial.in/
b1.addActionListener(this);
IT.addItemListener(this);
CE.addItemListener(this);
mech.addItemListener(this);
EE.addItemListener(this);
EC.addItemListener(this);
civil.addItemListener(this);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == b1)
{
repaint();
}
}
public void paint(Graphics g)
{
int i=10;
int k=60;
if(IT.getState()==true)
{
g.drawString("IT",10,k+=20);
}
if(CE.getState()==true)
{
g.drawString("CE",10,k+=20);
}
if(mech.getState()==true)
{
g.drawString("mech",10,k+=20);
}
if(EE.getState()==true)
{
g.drawString("EE",10,k+=20);
}
if(EC.getState()==true)
{
g.drawString("EC",10,k+=20);
}
if(civil.getState()==true)
{
g.drawString("civil",10,k+=20);
}
}
public void itemStateChanged(ItemEvent ie)
{
http://www.gtustudymaterial.in/
//repaint();
}
}
Create a list of vegetables. If you click on one of the items of the list,
the item should be displayed in a Textbox
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/*
<applet code="pract2" width=200 height=200>
</applet>
*/
public class pract2 extends Applet implements ItemListener
{
List list = null;
TextField a;
public void init()
{
a = new TextField( 70);
//create a multi select list
list = new List(5, true);
//add items to a list
list.add("potatoes,");
list.add("Brinjal,");
list.add("Cabbage,");
list.add("Carrot,");
list.add("Onion,");
list.add("Mint,");
list.add("potato,");
//add list
add(list);
add(a);
//add listener
list.addItemListener(this);
}
public void paint(Graphics g)
{
String[] items = list.getSelectedItems();
String msg = "";
for(int i=0; i < items.length; i++)
{
msg = items[i] + " " + msg;
http://www.gtustudymaterial.in/
}
a.setText("vegetables:"+ msg);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
}
Write JDBC program to insert the detail of college student in the MS-
Access database.
/**
/* database connectivity with MS-Access is done by creating
DataSourceName(dsn) in this example*/
/* Steps to use this example:
* go to ms-access and make a database called "student_base" and create
table named student_base.mdb
* 1. Go to Control Panel
2. Click on Administrative Tools(windows 2000/xp), Click on
ODBC(win98)
OR if u have (windows 7) than go to C:\Windows\SysWOW64\odbcad32.exe
3. click on ODBC
4. Then , you will see a ODBC dialog box. Click on UserDSn
5. Click on Add Button
6. Select Microsoft Access Driver(*.mdb) driver and click on finish
7. Give a Data Source Name : student_base
8. Then Click on Select
9. Browse on the database addItemDB.mdb file on your disk by downloading it
link provided..
will be stored
10. Click on OK.
Once the DSN is created, you can do this example*/
//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class addItemToDatabase extends JFrame
{
//Initializing Components
private JTextField inputs[];
private JButton add, reset;
private JLabel labels[];
private String fldLabel[] = {"First Name: ","Last Name: ","Branch","Enroll-no "};
http://www.gtustudymaterial.in/
private JPanel p1;
Connection con;
Statement st;
ResultSet rs;
String db;
//Setting up GUI
public addItemToDatabase()
{
//Setting up the Title of the Window
super("Adding Data to the Database");
//Set Size of the Window (WIDTH, HEIGHT)
setSize(300,180);
//Exit Property of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Constructing Components
inputs = new JTextField[4];
labels = new JLabel[4];
add = new JButton("Add");
reset = new JButton("Reset");
p1 = new JPanel();
//Setting Layout on JPanel 1 with 5 rows and 2 column
p1.setLayout(new GridLayout(5,2));
//Setting up the container ready for the components to be added.
Container pane = getContentPane();
setContentPane(pane);
//Setting up the container layout
GridLayout grid = new GridLayout(1,1,0,0);
pane.setLayout(grid);
//Creating a connection to MS Access and fetching errors using "try-catch" to
check if it is successfully connected or not.
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//db = "jdbc:odbc:Driver={Microsoft Access Driver
(*.mdb)};DBQ=addItemDB.mdb;";
con =
DriverManager.getConnection("jdbc:odbc:student_base");
st = con.createStatement();
JOptionPane.showMessageDialog(null,"Successfully
Connected to Database","Confirmation", JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,"Failed to
Connect to Database","Error Connection", JOptionPane.ERROR_MESSAGE);
System.exit(0);
http://www.gtustudymaterial.in/
}
//Constructing JLabel and JTextField using "for loop" in their desired order
for(int count=0; count<inputs.length && count<labels.length; count++) {
labels[count] = new JLabel(fldLabel[count]);
inputs[count] = new JTextField(20);
//Adding the JLabel and the JTextFied in JPanel 1
p1.add(labels[count]);
p1.add(inputs[count]);
}
//Implemeting Even-Listener on JButton add
add.addActionListener(new ActionListener()
{
//Handle JButton event if it is clicked
public void actionPerformed(ActionEvent event)
{

if (inputs[0].getText().equals("") ||
inputs[1].getText().equals("") || inputs[2].getText().equals("") || inputs[0].getText() == null
|| inputs[1].getText() == null || inputs[2].getText() == null)
JOptionPane.showMessageDialog(null,"Fill
up all the Fields","Error Input", JOptionPane.ERROR_MESSAGE);
else
try
{
String add = "insert into student
(firstName,LastName,Branch,Enroll_no) values
('"+inputs[0].getText()+"','"+inputs[1].getText()+"','"+inputs[2].getText()+"',"+inputs[3].get
Text()+")";
st.execute(add); //Execute the add sql
Integer.parseInt(inputs[3].getText());
//Convert JTextField Age in to INTEGER
JOptionPane.showMessageDialog(null,"Item
Successfully Added","Confirmation", JOptionPane.INFORMATION_MESSAGE);
}
catch (NumberFormatException e)
{

JOptionPane.showMessageDialog(null,"Please enter an integer on the Field
Enroll-no","Error Input", JOptionPane.ERROR_MESSAGE);
}
catch (Exception ei)
{

JOptionPane.showMessageDialog(null,"Failure to Add Item. Please Enter a
number on the Field Enroll-no","Error Input", JOptionPane.ERROR_MESSAGE);
}
http://www.gtustudymaterial.in/
}
}
);
//Implemeting Even-Listener on JButton reset
reset.addActionListener(new ActionListener()
{
//Handle JButton event if it is clicked
public void actionPerformed(ActionEvent event) {
inputs[0].setText(null);
inputs[1].setText(null);
inputs[2].setText(null);
inputs[3].setText(null);
}
}
);
//Adding JButton "add" and "reset" to JPanel 1 after the JLabel and
JTextField
p1.add(add);
p1.add(reset);
//Adding JPanel 1 to the container
pane.add(p1);
/**Set all the Components Visible.
* If it is set to "false", the components in the container will not be visible.
*/
setVisible(true);
}
//Main Method
public static void main (String[] args) {
addItemToDatabase aid = new addItemToDatabase();
}
}
Create a split pane which divides the frame into two parts. The first
part possesses a list and on selecting an item in a list, the item
should be displayed in the other portion.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
public class pract4
{
public static void main(String[] args)
{
JFrame frame = new SplitPaneFrame();
http://www.gtustudymaterial.in/
frame.show();
}
}
class SplitPaneFrame extends JFrame implements ListSelectionListener
{
public SplitPaneFrame()
{
setSize(400, 300);
list = new JList(texts);
list.addListSelectionListener(this);
description = new JTextArea();
JSplitPane innerPane= new
JSplitPane(JSplitPane.HORIZONTAL_SPLIT, list, description);
getContentPane().add(innerPane, "Center");
}
public void valueChanged(ListSelectionEvent event)
{
JList source = (JList)event.getSource();
Display value = (Display)source.getSelectedValue();
description.setText(value.getDescription());
}
private JList list;
private JTextArea description;
private Display[] texts =
{
new Display("Text1", "This is text1."),
new Display("Text2", "This is text2."),
new Display("Text3", "This is text3."),
new Display("Text4", "This is text4.")
};
}
class Display
{
public Display(String n, String t)
{
name = n;
des = t;
}
public String toString()
{
return name;
}
public String getDescription()
{
return des;
}
http://www.gtustudymaterial.in/
private String name;
private String des;
}

You might also like