0% found this document useful (0 votes)
25 views41 pages

JAVA 5 To 17

JAVA 5 to 17 PRACTICAL

Uploaded by

ssdsssaaa04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views41 pages

JAVA 5 To 17

JAVA 5 to 17 PRACTICAL

Uploaded by

ssdsssaaa04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Practical 5

Program Code:

1. Write a program which creates Menu of different colors and disable menu item for Black color.

import java.awt.*;
class Demo5 {
public static void main(String[] args) {
Frame f1=new Frame("Program code:");
f1.setSize(400,200);
f1.setVisible(true);
f1.setLayout(null);
MenuBar mb = new MenuBar();
Menu menu;
menu=new Menu("Colors");
MenuItem m1,m2,m3;
m1=new MenuItem("Red");
m2=new MenuItem("Orange");
m3=new MenuItem("Black");
m3.setEnabled(false);
menu.add(m1);
menu.add(m2);
menu.add(m3);
mb.add(menu);
f1.setMenuBar(mb);
}
}
OUTPUT:
Practical 5

XIII. Exercise

1. Find errors in following program and display output as shown below.


import java.awt.*;
import java.awt.event.*;
public class MenuDemo1 extends Frame
{
MenuBar mb;
MenuItem m1,m2,m3,m4;
Menu mn;
MenuShortcut ms;
MenuDemo1()
{
setTitle("MenuBar Demo");
setSize(500,500);
setLayout(null);
ms=new MenuShortcut(KeyEvent.VK_X);
mn=new Menu("File");
mb=new MenuBar();
m1=new MenuItem("New...");
m2=new MenuItem("Open...");
m3=new MenuItem("Save As...");
m4=new MenuItem("Exit",ms);
mn.add(m1);
mn.add(m2);
mn.add(m3);
mn.addSeparator();
mn.add(m4);
mb.add(mn);
setMenuBar(mb);
}
public static void main(String[] args)
{
MenuDemo1 md=new MenuDemo1();
md.setVisible(true);
}
}
OUTPUT:
Practical 6

X. Program Code:

1. Write a program code to generate the following outpu.


import javax.swing.*;
import java.awt.*;
class jcombo {
public static void main(String[] args) {
JFrame f = new JFrame("Ali Shaikh");
String s[]={"Solapur","Mumbai","Pune","Banglore"};
JComboBox jb = new JComboBox(s);
JLabel l= new JLabel("You Are in "+jb.getSelectedItem());
f.add(jb);
f.add(l);
f.setVisible(true);
f.setLayout(new FlowLayout());
f.setSize(600,600);
}
}

OUTPUT :
Practical 6

XIII. Exercise

1. Write a program to develop a frame to select the different states of India using JComboBox.
import javax.swing.*;
import java.awt.*;
class jcombo {
public static void main(String[] args) {
JFrame f = new JFrame("Ali Shaikh");
String s[]={"Solapur","Mumbai","Pune","Banglore"};
JComboBox jb = new JComboBox(s);
f.add(jb);
f.setVisible(true);
f.setLayout(new FlowLayout());
f.setSize(600,600);
}
}
OUTPUT:
Practical 6

2. Develop a program to demonstrate the use of ScrollPane in Swings


import javax.swing.*;
import java.awt.*;
class Simple {
public static void main(String[] args) {
JFrame frame = new JFrame("Simple JScrollPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
JTextArea textArea = new JTextArea();
textArea.setText("This is a simple example demonstrating JScrollPane in Swing.\n");
JScrollPane scrollPane = new JScrollPane(textArea);
frame.add(scrollPane);
frame.setVisible(true);
}
}
OUTPUT:
Practical 7

X. Program Code:

1. Develop a program to demonstrate the use of tree component in swing.

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
class Tree1{
public static void main(String[] args) {
JFrame fr = new JFrame("Ali Shaikh");
DefaultMutableTreeNode s =new DefaultMutableTreeNode("Programing Language");
DefaultMutableTreeNode c=new DefaultMutableTreeNode("Front End");
DefaultMutableTreeNode f=new DefaultMutableTreeNode("Back End");
DefaultMutableTreeNode r=new DefaultMutableTreeNode("HTML");
DefaultMutableTreeNode b=new DefaultMutableTreeNode("JAVA Script");
DefaultMutableTreeNode g=new DefaultMutableTreeNode("C++");
DefaultMutableTreeNode t=new DefaultMutableTreeNode("PHP");
JTree tr = new JTree(s);
s.add(c);
s.add(f);
s.add(r);
s.add(b);
s.add(g);
s.add(t);
fr.add(tr);
fr.setSize(400,400);
fr.setVisible(true);
}
}

OUTPUT:-
Practical 7

2. Write a program code to generate the following output

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
class Tree1{
public static void main(String[] args) {
JFrame fr = new JFrame("Ali Shaikh");
DefaultMutableTreeNode s =new DefaultMutableTreeNode("India");
DefaultMutableTreeNode c=new DefaultMutableTreeNode("Maharashra");
DefaultMutableTreeNode f=new DefaultMutableTreeNode("Mumbai");
DefaultMutableTreeNode r=new DefaultMutableTreeNode("Pune");
DefaultMutableTreeNode b=new DefaultMutableTreeNode("Nashik");
DefaultMutableTreeNode g=new DefaultMutableTreeNode("Nagpur");
DefaultMutableTreeNode t=new DefaultMutableTreeNode("Gujrath");
JTree tr = new JTree(s);
s.add(c);
c.add(f);
c.add(r);
c.add(b);
c.add(g);
s.add(t);
fr.add(tr);
fr.setSize(400,400);
fr.setVisible(true);
}
}

OUTPUT:-
Practical 7

XIII. Exercise

1. Write a Jtree program to show root directory and its subFolders of your System.
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
class Tree1{
public static void main(String[] args) {
JFrame fr = new JFrame("Ali Shaikh");
DefaultMutableTreeNode s =new DefaultMutableTreeNode("SVSMD's College ");
DefaultMutableTreeNode c=new DefaultMutableTreeNode("Div A");
DefaultMutableTreeNode f=new DefaultMutableTreeNode("Mahi");
DefaultMutableTreeNode r=new DefaultMutableTreeNode("Pritam");
DefaultMutableTreeNode b=new DefaultMutableTreeNode("Jadhav");
DefaultMutableTreeNode g=new DefaultMutableTreeNode("Samrudhi");
DefaultMutableTreeNode t=new DefaultMutableTreeNode("Div B");
JTree tr = new JTree(s);
s.add(c);
c.add(f);
c.add(r);
t.add(b);
t.add(g);
s.add(t);
fr.add(tr);
fr.setSize(400,400);
fr.setVisible(true);
}
}
OUTPUT:-
Practical 8

Program Code:

1. Develop a program to demonstrate the use of JTable.


import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Table_Example {
JFrame f;
Table_Example() {
f=new JFrame(“Ali Shaikh");
String data[][]= {
{"101","Amit","670000"},
{"102","Jai","780000"},
{"103","Sachin","700000"}
};
String column[]= {"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true); }
public static void main(String args[]) {
new Table_Example();
}
}

OUTPUT :-
Practical 8

2. Write a program code to generate the following output

import javax.swing.JFrame;

import javax.swing.JScrollPane;

import javax.swing.JTable;

public class Table_Example {

JFrame f;

Table_Example() {

f=new JFrame(“Ali Shaikh");

String data[][]= {

{"101","Amit","670000"},

{"102","Jai","780000"},

{"103","Sachin","700000"}

};

String column[]= {"ID","NAME","SALARY"};

JTable jt=new JTable(data,column);

jt.setBounds(30,40,200,300);

JScrollPane sp=new JScrollPane(jt);

f.add(sp);

f.setSize(300,400);

f.setVisible(true); }

public static void main(String args[]) {

new Table_Example();

OUTPUT :-
Practical 8

XIII. Exercise :
1. Write a Java program to create a table of Name of Student, Percentage and Grade of 10
students using JTable.
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class percentage {
JFrame f;
percentage() {
f=new JFrame("Ali Shaikh");
String data[][]={{"MAAZ MODAK","70%","A"},
{"PRITAM GHODAKE","78%","A+"},
{"MAHIFUZ PATHAN","77%","A+"},
{"IRFAN MAKANDAR","80%","A+"},
{"HARSHAD KEDAR","77%","A+"},
{"YOSHIK KARNAWAT","76%","A+"},
{"SATYAJEET NIKAM","78","A+"},
{"ABHISHEK MARANE","67","B"},
{"ALI SHAIKH","77","A+"},
{"ADI SIDHYAE","76","A+"}};
String column[]= {"NAME","PERCENTAGE","GRADE"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String args[]) {
new percentage();
}
}

OUTPUT :-
Practical 9

Program Code:

1. Write a program code to generate the following output.


import javax.swing.JFrame;
import javax.swing.JProgressBar;
public class pb extends JFrame {
JProgressBar jb;
int i=0,num=0;
pb() {
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,160,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setLayout(null);
}
public void iterate(){
while(i<=2000) {
jb.setValue(i);
i=i+20;
}
}
public static void main(String[] args) {
pb m = new pb();
m.setVisible(true);
m.iterate();
}
}

OUTPUT :-
Practical 9

XIII. Exercise

1. Develop a program to demonstrate the use of JProgressBar.


import javax.swing.JFrame;
import javax.swing.JProgressBar;
public class pb extends JFrame {
JProgressBar jb;
int i=0,num=0;
pb() {
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,160,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setLayout(null);
}
public void iterate(){
while(i<=2000) {
jb.setValue(i);
i=i+20;
}
}
public static void main(String[] args) {
pb m = new pb();
m.setVisible(true);
m.iterate();
}
}

OUTPUT :-
Practical 9

2. Write a Program using JProgressBar to show the progress of Progressbar when user clicks on
JButton.
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class ProgressBarExample extends JFrame {
private JProgressBar progressBar = new JProgressBar(0, 100);
private JButton startButton = new JButton("Start Progress");
public ProgressBarExample() {
setTitle("Progress Bar Example");
setSize(300, 150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
progressBar.setStringPainted(true);
add(progressBar);
add(startButton);
startButton.addActionListener(e -> new SwingWorker<Void, Integer>() {
protected Void doInBackground() {
for (int i = 0; i <= 100; i++) {
try { Thread.sleep(50); } catch (InterruptedException ignored) {}
publish(i);
}
return null;
}
protected void process(java.util.List<Integer> chunks) {
chunks.forEach(progressBar::setValue);
}
protected void done() {
JOptionPane.showMessageDialog(null, "Task Completed!");
}
}.execute());
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new ProgressBarExample().setVisible(true);
});
}
}

OUTPUT :-
Practical 10

Program Code:

1. Write a program to generate KeyEvent when a key is pressed and display “Key Pressed”
message.
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class KeyEventExample extends JFrame implements KeyListener {
private JLabel messageLabel,messageLabel1;
public KeyEventExample() {
setTitle("Key Event Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
messageLabel = new JLabel("Press any key...");
add(messageLabel);
addKeyListener(this);
setVisible(true); }
@Override
public void keyPressed(KeyEvent e) {
messageLabel.setText("Key Pressed: " + KeyEvent.getKeyText(e.getKeyCode()));
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
public static void main(String[] args) {
new KeyEventExample();
}
}

OUTPUT :-
Practical 10

2. Develop a program which will implement special keys such as function keys and arrow keys.
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class SpecialKeysExample extends JFrame implements KeyListener {
private JLabel messageLabel;
public SpecialKeysExample() {
setTitle("Special Keys Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
messageLabel = new JLabel("Press a special key...");
add(messageLabel);
addKeyListener(this);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
String keyText = KeyEvent.getKeyText(e.getKeyCode());
messageLabel.setText("Key Pressed: " + keyText);
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public static void main(String[] args) {
new SpecialKeysExample();
}
}

OUTPUT :-
Practical 10

XIII. Exercise :

3. Develop a program to accept two numbers and display product of two numbers when user
pressed “Multiply” button.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
class SimpleCalculator extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField tField1, tField2;
private JLabel label
public SimpleCalculator(String title) {
setTitle(title);
setLayout(new FlowLayout());
tField1 = new JTextField(10);
tField2 = new JTextField(10);
JButton button = new JButton("Multiply");
label = new JLabel("");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int val1 = Integer.parseInt(tField1.getText());
int val2 = Integer.parseInt(tField2.getText());
label.setText("Answer: " + (val1 * val2));
} catch (NumberFormatException ex) {
label.setText("Invalid input!");
}
}
});
add(tField1);
add(tField2);
add(button);
add(label);
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);}
public static void main(String[] args) {
new SimpleCalculator("Simple Multiplier");
}}

OUTPUT :-
Practical 11

X. Program Code:

1. Debug the following Program code and write the output.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MouseDemo extends JFrame implements MouseListener {
JLabel label;
public MouseDemo() {
setTitle("Mouse Demo");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
label = new JLabel("Hello Mouse");
add(label);
addMouseListener(this);
setVisible(true); // Make the frame visible
}
public void mousePressed(MouseEvent e) {
label.setText("Mouse Pressed: " + e.getClickCount() + " at position " + e.getX() + ", " + e.getY());
}
public void mouseReleased(MouseEvent e) {
label.setText("Mouse Released: # of clicks: " + e.getClickCount());
}
public void mouseEntered(MouseEvent e) {
label.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
label.setText("Mouse Exited");
}
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked: # of clicks: " + e.getClickCount());
}
public static void main(String[] args) {
new MouseDemo(); // Create an instance of the MouseDemo frame
}
}
OUTPUT:-
Practical 11

XIII. Exercise :
1. Write a program to change the background color of Applet when user performs events using
Mouse.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ColorChangeFrame extends JFrame implements MouseListener {
public ColorChangeFrame() {
setTitle("Color Change Frame");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
getContentPane().setBackground(Color.WHITE);
addMouseListener(this);
setVisible(true);
}
public void mousePressed(MouseEvent e) {
getContentPane().setBackground(Color.RED);
}
public void mouseReleased(MouseEvent e) {
getContentPane().setBackground(Color.GREEN);
}
public void mouseEntered(MouseEvent e) {
getContentPane().setBackground(Color.BLUE);
}
public void mouseExited(MouseEvent e) {
getContentPane().setBackground(Color.YELLOW);
}
public void mouseClicked(MouseEvent e) {
getContentPane().setBackground(Color.ORANGE);
}
public static void main(String[] args) {
new ColorChangeFrame();
}
}
Output:
Practical 11

2. Write a program to count the number of clicks performed by the user in a Frame window.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClickCounter extends JFrame implements MouseListener {
private JLabel label;
private int clickCount = 0;
public ClickCounter() {
setTitle("Click Counter");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
label = new JLabel("Click Count: 0");
add(label);
addMouseListener(this);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
clickCount++;
label.setText("Click Count: " + clickCount);
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public static void main(String[] args) {
new ClickCounter();
}
}
OUTPUT:-
Practical 11

3. Write a program to demonstrate the use of mouseDragged and mouseMoved method of


MouseMotionListener.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MouseMotionDemo extends JFrame implements MouseMotionListener {
private JLabel label;
public MouseMotionDemo() {
setTitle("Mouse Motion Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
label = new JLabel("Move or Drag the Mouse");
add(label);
addMouseMotionListener(this);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
label.setText("Mouse Dragged at: X = " + e.getX() + ", Y = " + e.getY());
}
public void mouseMoved(MouseEvent e) {
label.setText("Mouse Moved at: X = " + e.getX() + ", Y = " + e.getY());
}
public static void main(String[] args) {
new MouseMotionDemo();
}
}
OUTPUT:-
Practical 12

Program Code:

1. Write a program using JPasswordField to set the password character as ‘#’ instead of ‘*’.

import javax.swing.*;
public class PasswordFieldDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Password Field Demo");
JPasswordField passwordField = new JPasswordField(15);
passwordField.setEchoChar('*');

JButton button = new JButton("Submit");


button.addActionListener(e ->
JOptionPane.showMessageDialog(frame, "Password: " + new
String(passwordField.getPassword()))
);

frame.setLayout(new java.awt.FlowLayout());
frame.add(passwordField);
frame.add(button);
frame.setSize(300, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
OUTPUT:-
Practical 12

XIII. Exercise :
1. Write a program using JPasswordField and JTextField to demonstrate the use of user
authentication.
import javax.swing.*;
public class UserAuthDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("User Authentication");
JTextField userField = new JTextField(15);
JPasswordField passField = new JPasswordField(15);
passField.setEchoChar('#');
JButton loginButton = new JButton("Login");
loginButton.addActionListener(e -> {
String message = ("admin".equals(userField.getText()) && "password".equals(new
String(passField.getPassword())))
? "Login Successful!"
: "Invalid Username or Password.";
JOptionPane.showMessageDialog(frame, message);
});
frame.setLayout(new java.awt.FlowLayout());
frame.add(new JLabel("Username:"));
frame.add(userField);
frame.add(new JLabel("Password:"));
frame.add(passField);
frame.add(loginButton);
frame.setSize(300, 120);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
OUTPUT:-
Practical 12

2. Write a program using JTextField to perform the addition of two numbers.


import javax.swing.*;
import java.awt.event.*;
public class AdditionDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Addition of Two Numbers");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new java.awt.FlowLayout());
JTextField num1Field = new JTextField(10);
JTextField num2Field = new JTextField(10);
JButton addButton = new JButton("Add");
JLabel resultLabel = new JLabel("Result: ");
addButton.addActionListener(e -> {
try {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int sum = num1 + num2;
resultLabel.setText("Result: " + sum);
} catch (NumberFormatException ex) {
resultLabel.setText("Please enter valid numbers");
}
});
frame.add(new JLabel("Number 1:"));
frame.add(num1Field);
frame.add(new JLabel("Number 2:"));
frame.add(num2Field);
frame.add(addButton);
frame.add(resultLabel);
frame.setVisible(true); // Make the frame visible
}
}
OUTPUT:-
Practical 12

3. Write a program using JPasswordField to accept password from user and if the length is less
than 6 characters then error message should be displayed “Password length must be >6
characters”.
import javax.swing.*;
public class PasswordLengthCheck {
public static void main(String[] args) {
JFrame frame = new JFrame("Password Length Check");
JPasswordField passwordField = new JPasswordField(15);
JButton submitButton = new JButton("Submit");
submitButton.addActionListener(e -> {
String password = new String(passwordField.getPassword());
if (password.length() < 6) {
JOptionPane.showMessageDialog(frame, "Password length must be > 6 characters");
} else {
JOptionPane.showMessageDialog(frame, "Password accepted");
}
});
frame.setLayout(new java.awt.FlowLayout());
frame.add(new JLabel("Enter Password:"));
frame.add(passwordField);
frame.add(submitButton);
frame.setSize(300, 120);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
OUTPUT:-
Practical 13

Program Code:

1. Debug the following code and write the output of following code.

import java.awt.*;
import java.awt.event.*;
public class WindowDemo
{
Frame f;
WindowDemo()
{
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
f.dispose();
}
};
f.setSize(400,400);
f.setLayout(null);
f.setVisible(false);
}
public static void main(String[] args)
{
new WindowDemo();
}
}
OUTPUT:-
Practical 13

XIII. Exercise :
1. Write a program to demonstrate the use of WindowAdapter class.
import java.awt.*;
import java.awt.event.*;
public class WindowAdapterDemo {
public static void main(String[] args) {
Frame frame = new Frame("Window Adapter Demo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
frame.dispose();
}
});
frame.setSize(400, 300);
frame.setLayout(new FlowLayout());
frame.add(new Label("Close this window using the close button!"));
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
System.out.println("Window opened!");
}
});
}
}
OUTPUT:-
Practical 13

2. Write a program to demonstrate the use of anonymous inner class.


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class AnonymousInnerClassDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Anonymous Inner Class Demo");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
JButton button = new JButton("Click Me!");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Button Clicked!");
}
});
frame.add(button);
frame.setVisible(true);
}
}
OUTPUT:-
Practical 13

3. Write a program using MouseMotionAdapter class to implement only one method


mouseDragged().
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MouseMotionAdapterDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Mouse Motion Adapter Demo");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
JLabel label = new JLabel("Drag the mouse inside the frame");
label.setBounds(50, 20, 300, 20);
frame.add(label);
frame.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
label.setText("Mouse Dragged at: X = " + e.getX() + ", Y = " + e.getY());
}
});
frame.setVisible(true);
}
}
OUTPUT:-
Practical 14

Program Code:

1. Execute the following code and write the output.


import java.io.*;
import java.net.*;
public class InetDemo
{
public static void main(String[] args)
{
try
{
InetAddress ip=InetAddress.getByName("localhost");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}
catch(Exception e){System.out.println(e);}
}
}
OUTPUT:-

XIII. Exercise :
1. Develop a program using InetAddress class to retrieve IP address of computer when hostname is
entered by the user.
import java.net.*;
import java.util.Scanner;
public class IPAddressRetriever {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter hostname: ");
String hostname = scanner.nextLine();
try {
InetAddress inetAddress = InetAddress.getByName(hostname);
System.out.println("IP Address of " + hostname + " is: " + inetAddress.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("Host not found: " + hostname);
} finally {
scanner.close();
}
}
}
OUTPUT:-
Practical 15

Program Code:

1. Execute the following code and write the output.

import java.net.*;
class URLDemo
{
public static void main(String args[]) throws MalformedURLException
{
URL hp = new URL("https://www.javatpoint.com/javafx-tutorial");
System.out.println("Protocol: " + hp.getProtocol());
System.out.println("Port: " + hp.getPort());
System.out.println("Host: " + hp.getHost());
System.out.println("File: " + hp.getFile());
System.out.println("Ext:" + hp.toExternalForm());
}
}
OUTPUT:-

XIII. Exercise :
1. Write a program using URL class to retrieve the host, protocol, port and file of URL
http://www.msbte.org.in.
import java.net.*;
public class URLInfoRetriever {
public static void main(String[] args) {
try {
URL url = new URL("http://www.msbte.org.in");
String protocol = url.getProtocol();
String host = url.getHost();
int port = url.getPort() == -1 ? 80 : url.getPort(); // Default port for HTTP
String file = url.getFile();
System.out.println("Protocol: " + protocol);
System.out.println("Host: " + host);
System.out.println("Port: " + port);
System.out.println("File: " + file);
} catch (MalformedURLException e) {
System.out.println("Invalid URL");
}
}
}
OUTPUT:
Practical 15

2. Write a program using URL and URLConnection class to retrieve the date, content type, content
length information of any entered URL.
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class URLInfoRetriever {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a URL: ");
String urlString = scanner.nextLine();
try {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
long date = connection.getDate();
String contentType = connection.getContentType();
int contentLength = connection.getContentLength();
System.out.println("Date: " + (date == 0 ? "Not available" : new java.util.Date(date)));
System.out.println("Content Type: " + contentType);
System.out.println("Content Length: " + (contentLength == -1 ? "Not available" :
contentLength + " bytes"));
} catch (MalformedURLException e) {
System.out.println("Invalid URL format.");
} catch (IOException e) {
System.out.println("Error retrieving information from the URL.");
} finally {
scanner.close();
}
}
}
OUTPUT:-
Practical 16

Program Code:
1. Write a program to check credentials of users (Client will send user id and password to server and
server will authenticate the client using equals()).
 Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(12345)) {
while (true) {
try (Socket socket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true)) {

String userId = reader.readLine();


String password = reader.readLine();
writer.println("user".equals(userId) && "pass".equals(password) ? "Authentication
Successful!" : "Authentication Failed!");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
 Client.java
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 12345);
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
Scanner scanner = new Scanner(System.in)) {

System.out.print("Enter User ID: ");


writer.println(scanner.nextLine());
System.out.print("Enter Password: ");
writer.println(scanner.nextLine());
System.out.println(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}}
Practical 16

OUTPUT:-
First Start The Server

Execution

XIII. Exercise :
1. Write a program using Socket and ServerSocket to create Chat Application.
 Server.java
import java.io.*;
import java.net.*;
public class ChatServer {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(12345);
Socket socket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in))) {
System.out.println("Server connected");
String clientMessage;
while (true) {
clientMessage = reader.readLine();
if (clientMessage.equalsIgnoreCase("exit")) break;
System.out.println("Client: " + clientMessage);
System.out.print("Server: ");
writer.println(consoleReader.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Practical 16

 Client.java
import java.io.*;
import java.net.*;

public class ChatClient {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 12345);
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in))) {

String clientMessage;
while (true) {
System.out.print("Client: ");
clientMessage = consoleReader.readLine();
writer.println(clientMessage);
if (clientMessage.equalsIgnoreCase("exit")) break;
System.out.println("Server: " + reader.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
OUTPUT:
Practical 16

2. Write a program to develop prime number Server (Client will send any number to server, Sever
will send the response the number is prime or not).
 Server.java
import java.io.*;
import java.net.*;
public class PrimeNumberServer {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(12345)) {
System.out.println("Prime Number Server is running...");
while (true) {
try (Socket socket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true)) {

int number = Integer.parseInt(reader.readLine());


writer.println(isPrime(number) ? "Prime" : "Not Prime");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static boolean isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i * i <= num; i++) if (num % i == 0) return false;
return true;
}
}}
 Client.java
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class PrimeNumberClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 12345);
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter a number: ");
writer.println(scanner.nextInt());
System.out.println(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}}
Practical 16

OUTPUT:-
Practical 17

Program Code:
1. Execute the following Program and write the output.
 Server.java
import java.net.*;
public class DgramRec
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}
 Client.java
import java.net.*;
public class DGramSender
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket();
String str = "Java is Easy!!!!!";
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(),
ip, 3000);
ds.send(dp);
ds.close();
}
}
OUTPUT:-
Practical 17

XIII. Exercise :
1. Write a program using DatagramPacket and DatagramSocket to create chat application.
 Server.java
import java.net.*;
public class ChatServer {
public static void main(String[] args) {
try (DatagramSocket socket = new DatagramSocket(12345)) {
byte[] buffer = new byte[1024];
System.out.println("Server is running...");
while (true) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
System.out.println("Client: " + new String(packet.getData(), 0, packet.getLength()));
String response = "Message received!";
socket.send(new DatagramPacket(response.getBytes(), response.length(), packet.getAddress(),
packet.getPort()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
 Client.java
import java.net.*;
import java.util.Scanner;
public class ChatClient {
public static void main(String[] args) {
try (DatagramSocket socket = new DatagramSocket()) {
Scanner scanner = new Scanner(System.in);
byte[] buffer;
while (true) {
System.out.print("Client: ");
String message = scanner.nextLine();
socket.send(new DatagramPacket(message.getBytes(), message.length(),
InetAddress.getByName("localhost"), 12345));
if (message.equalsIgnoreCase("exit")) break;
buffer = new byte[1024];
socket.receive(new DatagramPacket(buffer, buffer.length));
System.out.println("Server: " + new String(buffer).trim());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
OUTPUT:
Practical 17

2. Write a program using DatagramPacket and DataGramSocket to copy the contents of one file
into other.
 Server.java
import java.io.*;
import java.net.*;
public class FileCopyServer {
public static void main(String[] args) {
try (DatagramSocket socket = new DatagramSocket(12345);
FileOutputStream fos = new FileOutputStream("output.txt")) {
byte[] buffer = new byte[1024];
System.out.println("Server is running...");
while (true) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
if (new String(packet.getData(), 0, packet.getLength()).equals("END")) break;
fos.write(packet.getData(), 0, packet.getLength());
}
System.out.println("File copied successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
 Client.java
import java.io.*;
import java.net.*;
public class FileCopyClient {
public static void main(String[] args) {
try (DatagramSocket socket = new DatagramSocket();
FileInputStream fis = new FileInputStream("input.txt")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
socket.send(new DatagramPacket(buffer, bytesRead, InetAddress.getByName("localhost"),
12345));
}
socket.send(new DatagramPacket("END".getBytes(), 3, InetAddress.getByName("localhost"),
12345));
System.out.println("File sent successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
OUTPUT:-
Practical 17

3. Write a program using DatagramPacket and DatagramSocket to transfer the file from one
location to another.
 Server.java
import java.io.*;
import java.net.*;
public class FileTransferServer {
public static void main(String[] args) {
try (DatagramSocket socket = new DatagramSocket(12345);
FileOutputStream fos = new FileOutputStream("received_file.txt")) {
byte[] buffer = new byte[1024];
System.out.println("Server is running...");
while (true) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
if (new String(packet.getData(), 0, packet.getLength()).equals("END")) break;
fos.write(packet.getData(), 0, packet.getLength());
}
System.out.println("File transferred!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
 Client.java
import java.io.*;
import java.net.*;
public class FileTransferClient {
public static void main(String[] args) {
try (DatagramSocket socket = new DatagramSocket();
FileInputStream fis = new FileInputStream("source_file.txt")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
socket.send(new DatagramPacket(buffer, bytesRead, InetAddress.getByName("localhost"),
12345));
}
socket.send(new DatagramPacket("END".getBytes(), 3, InetAddress.getByName("localhost"),
12345));
System.out.println("File sent!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
OUTPUT:-

You might also like