Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
217 views

Java Lab Report

The document contains lab reports submitted by Jitendra Kumar Yadav for an Advance Java Programming course. It includes summaries of programs written for two labs. Lab 1 programs focus on drawing shapes and text using graphics and swing. Lab 2 programs implement swing features like input dialogs, message dialogs, menus and event handling. The document lists the questions assigned for each lab and provides code snippets and output for the programs submitted as answers.

Uploaded by

bishalgc167
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
217 views

Java Lab Report

The document contains lab reports submitted by Jitendra Kumar Yadav for an Advance Java Programming course. It includes summaries of programs written for two labs. Lab 1 programs focus on drawing shapes and text using graphics and swing. Lab 2 programs implement swing features like input dialogs, message dialogs, menus and event handling. The document lists the questions assigned for each lab and provides code snippets and output for the programs submitted as answers.

Uploaded by

bishalgc167
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

MEGA NATIONAL

COLLEGE
KUMARIPATI , LALITPUR

Lab Report on

Advance Java Programing

Submitted by: Jitendra kumar yadav Checked by internal

…………………………….

Checked by external

…………………………….

1
TABLE CONTENT
1. LAB 1
 Write a program to draw line , rectangle and ellipse using graphics 2D
in swing…………………………………………………..
 Write a program to render string " Mega college" in panel use font
style and color on it………………………………………………..
 Write a program to draw a rectangle and ellipse and fill different
color on it………………………………………………………….
 Write a program to display all font family of graphic Environment
……………………….
 Write a program to draw line , rectangle , circle and ellipse using
graphics in swing . ……………………………………………….
.
2. LAB
 Write a swing program to read two input from user input dialog and
sum those values and display it using message dialog…………….
 Write a swing program to create Menus. …………………………..
 Write a swing program to get two number input using two text field
and multiply it by clicking button and display it in third text
field………………………………………………………………..
 Write a swing program to connect database and display student
details in Jtable ………………………………………………….
 Write a database program to implementing RowSet ……………
 Write a swing program to implement multiple mouse event.
…………………………………………………………………….
 Write a swing program to implement layout manager
………………………………………………………………….
 Write a swing prgram to check login validation by using database.
 Create distributed system Using RMI. ……………………………

2
3
LAB 1
Question1. Write a program to draw line , rectangle and ellipse using graphics 2D In swing .

import javax.swing.*;

import java.awt.*;

import java.awt.geom.Ellipse2D;

class Shape extends JFrame {

public Shape() {

super("Rectangles Drawing Demo");

getContentPane().setBackground(Color.WHITE);

setSize(480, 200);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null);

void drawShapes(Graphics g) {

Graphics2D g2d = (Graphics2D) g;

g2d.setColor(Color.red); //code to draw rectangle

g2d.drawRect(200, 200, 200, 200); //code to draw line

g2d.drawLine(50, 50, 200, 180); //code to draw ellipse

g2d.draw(new Ellipse2D.Double(400, 400, 250, 250));

public void paint(Graphics g) {

super.paint(g);

drawShapes(g);

public static void main(String[] args) throws Exception {

4
SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

new Shape().setVisible(true);

} });

}}

Question 2 Write a program to render string "KCT college" in panel use font style

and color on it.

Code

import javax.swing.*;

import java.awt.*;

class Draw_Text extends JPanel {

public static void main(String args[]) {

JFrame frame = new JFrame("Draw a Text");

frame.setSize(300, 300);

frame.getContentPane().setBackground(Color.white);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Draw_Text obj = new Draw_Text();

frame.add(obj); frame.setVisible(true);}

@Override

public void paintComponent(Graphics g) {

g.setColor(Color.black);

Font myFont = new Font("lato", Font.BOLD, 40);

g.setFont(myFont);

g.setColor(Color.blue);

5
g.drawString("KCT COLLEGE", 20, 90);}}

Question 3 Write a program to draw a rectangle and ellipse and fill different color

on it.

Code

import javax.swing.*;

import java.awt.*;

import java.awt.geom.Ellipse2D;

class Shape extends JFrame {

public Shape() {

super("Rectangles Drawing Demo");

getContentPane().setBackground(Color.WHITE);

setSize(480, 200);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null);

void drawShapes(Graphics g) {

Graphics2D g2d = (Graphics2D) g;

Graphics2D g2 = (Graphics2D) g;

6
g2d.setColor(Color.blue);

//code to draw rectangle

g2d.fillRect(200, 200, 200, 200);

//code to draw ellipse

g2d.fill(new Ellipse2D.Double(400, 400, 250, 250));

public void paint(Graphics g) {

super.paint(g);

drawShapes(g);

public static void main(String[] args) throws Exception {

SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

new Shape().setVisible(true);

} }); }}

Output

7
Question 4 .

Write a program to display all font family of graphic Environment.

Code

import java.awt.GraphicsEnvironment;

public class Main {

public static void main(String[] args) {

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

String familyNames[] = ge.getAvailableFontFamilyNames();

for (String familyName : familyNames) {

System.out.println("Family names: " + familyName);

}}}

OUTPUT

C:\Users\97798\.jdks\corretto-16.0.2\bin\java.exe "-javaagent:C:\Program Files\JetBrains\IntelliJ

IDEA 2021.3.2\lib\idea_rt.jar=51678:C:\Program Files\JetBrains\IntelliJ IDEA 2021.3.2\bin" -

Dfile.encoding=UTF-8 -classpath C:\Users\97798\IdeaProjects\lab1\out\production\lab1 Main

Family names: 0 Cube a Rama DNA

Family names: 0Surendra

Family names: 11S01 Black Tuesday

Family names: 1980 Portable

Family names: 20th Centenary Faux

Family names: 20th Century Font

Family names: A Charming Font

Family names: A Charming Font Expanded

8
Family names: A Charming Font Italic

Family names: A Charming Font Leftleaning

Family names: A Charming Font Outline

Family names: A Charming Font Superexpanded

Family names: A Cut Above The Rest

Family names: A Yummy Apology

Family names: A.C.M.E. Secret Agent

Family names: A750-Sans

Family names: A750-Sans-Cd-Light

Process finished with exit code 0

5. Write a program to draw line, rectangle, circle and ellipse using graphics in

swing.

Code

import java.awt.*;

import javax.swing.JFrame;

class Main extends Canvas{ public void paint(Graphics g) {

setBackground(Color.WHITE); setForeground(Color.BLACK);

g.drawLine(20,20,80,80);

g.drawRect(100,100,100,100);

g.drawOval(200, 200, 100, 100);

public static void main(String[] args) {

Main m=new Main();

JFrame f=new JFrame("Shapes in swing");

f.add(m);

9
f.setSize(400,400);

f.setVisible(true);

Output

10
LAB 2
1. Write a swing program to read two input from user using input dialog and sum

those values and display it using message dialog.

Code

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

class Addition extends JFrame implements ActionListener{

JLabel label1, label2, label3;

JTextField jt1, jt2;

JButton submit;

Addition(){

setTitle("User input");

setSize(700,500);

setLocationRelativeTo(null);

setDefaultCloseOperation(EXIT_ON_CLOSE);

Container c = getContentPane();

c.setLayout(null);

label1 = new JLabel("Enter 1st num:");

label1.setBounds(20,50,100,20);

c.add(label1);

11
jt1=new JTextField();

jt1.setBounds(130,50,100,20);

c.add(jt1);

label2 = new JLabel("Enter 2nd num:");

label2.setBounds(20,100,100,20);

c.add(label2);

jt2=new JTextField();

jt2.setBounds(130,100,100,20);

c.add(jt2);

label3 = new JLabel("hello");

submit = new JButton("Calculate");

submit.setBounds(130,200,80,20);

c.add(submit);

submit.addActionListener(this);

setVisible(true);

@Override

public void actionPerformed(ActionEvent e) {

int a = Integer.parseInt(jt1.getText());

int b = Integer.parseInt(jt2.getText());

int c = 0;

if (e.getSource().equals(submit)) {

c = a + b;

label3.setText(String.valueOf(c));

JOptionPane.showMessageDialog(new JFrame(), label3);

12
}

class Main {

public static void main(String[] args) {

Addition a = new Addition();

2. Write a swing program to create Menus.

Code.

import javax.swing.*;

import java.awt.event.*;

class Main {

public static JMenuBar createMenuBar() {

JMenuBar menuBar;

JMenu menu, submenu;

JMenuItem menuItem;

13
JRadioButtonMenuItem rdmi;

JCheckBoxMenuItem cbmi;

//Create the menu bar.

menuBar = new JMenuBar();

//Build the File Menu.

menu = new JMenu("File");

menu.setMnemonic(KeyEvent.VK_F);

menu.getAccessibleContext().setAccessibleDescription("Dealing with Files");

menuBar.add(menu);

//a group of JMenuItems

menuItem = new JMenuItem("New Project...",

new ImageIcon("images/newproject.png"));

menuItem.setMnemonic(KeyEvent.VK_P);

menuItem.setAccelerator(KeyStroke.getKeyStroke(

KeyEvent.VK_1, ActionEvent.ALT_MASK));

menuItem.getAccessibleContext().setAccessibleDescription(

"New Project");

menu.add(menuItem);

menuItem = new JMenuItem("New File...",

new ImageIcon("images/newfile.png"));

menuItem.setMnemonic(KeyEvent.VK_F);

menu.add(menuItem);

//a group of check box menu items

menu.addSeparator();

14
cbmi = new JCheckBoxMenuItem("A check box menu item");

cbmi.setMnemonic(KeyEvent.VK_C);

menu.add(cbmi);

cbmi = new JCheckBoxMenuItem("Another one");

cbmi.setMnemonic(KeyEvent.VK_H);

menu.add(cbmi);

//Build Edit menu in the menu bar.

menu = new JMenu("Edit");

menu.setMnemonic(KeyEvent.VK_E);

menu.getAccessibleContext().setAccessibleDescription(

"Edit Menu");

menuBar.add(menu);

return menuBar;

public static void main(String[] args) {

final JFrame frame = new JFrame("Menu Demo");

frame.setJMenuBar(createMenuBar());

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(500, 300);

frame.setVisible(true);

Output

15
3. Write a swing program to get two number input using two text field and

multiply it by clicking button and display it in third text field.

Code

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

class Mult extends JFrame implements ActionListener{

JLabel label1, label2, label3;

JTextField jt1, jt2;

JButton submit;

Mult(){

setTitle("User input");

setSize(700,500);

setLocationRelativeTo(null);

setDefaultCloseOperation(EXIT_ON_CLOSE);

Container c = getContentPane();

16
c.setLayout(null);

label1 = new JLabel("Enter First number:");

label1.setBounds(20,50,100,20);

c.add(label1);

jt1=new JTextField();

jt1.setBounds(130,50,100,20);

c.add(jt1);

label2 = new JLabel("Enter Second number:");

label2.setBounds(20,100,100,20);

c.add(label2);

jt2=new JTextField();

jt2.setBounds(130,100,100,20);

c.add(jt2);

label3 = new JLabel("Total is ");

label3.setBounds(20, 150, 100 ,20);

c.add(label3);

submit = new JButton("Calculate");

submit.setBounds(150,200,90,30);

c.add(submit);

submit.addActionListener(this);

setVisible(true);

@Override

public void actionPerformed(ActionEvent e) {

if(jt1.getText().isEmpty()){

17
JOptionPane.showMessageDialog(new JFrame(), "please enter first number");

return;

if(jt2.getText().isEmpty()){

JOptionPane.showMessageDialog(new JFrame(), "please enter second number");

return;

int a = Integer.parseInt(jt1.getText());

int b = Integer.parseInt(jt2.getText());

int c = 0;

if (e.getSource().equals(submit)) {

c = a * b;

label3.setText("Total is: " + c);

class Main {

public static void main(String[] args) {

Mult m = new Mult();

Output

18
4. Write a swing program to connect database and display student details in JTable.

Code

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

public class DbConnector {

public static void main(String[] args) {

try{

Class.forName("com.mysql.jdbc.Driver");

Connection con= DriverManager.getConnection(

"jdbc:mysql://localhost:3306/tu","root","");

System.out.println("Database connected");

//here sonoo is database name, root is username and password

Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("select * from student");

while(rs.next())

System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+"

19
"+rs.getString(4)+" "+rs.getString(5));

con.close();

}catch(Exception e){ System.out.println(e);}

OUTPUT

5. Write a database program to implementing RowSet.

Code.

import java.sql.Connection;

import java.sql.DriverManager;

20
import java.sql.ResultSet;

import java.sql.Statement;

public class DbConnector {

public static void main(String[] args) {

try{

Class.forName("com.mysql.jdbc.Driver");

Connection con= DriverManager.getConnection(

"jdbc:mysql://localhost:3306/tu","root","");

System.out.println("Database connected");

//here sonoo is database name, root is username and password

Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("select * from student");

while(rs.next())

System.out.println(rs.getInt(1)+" "+rs.getString(2)+"

"+rs.getString(3)+" "+rs.getString(4)+" "+rs.getString(5));

con.close();

}catch(Exception e){ System.out.println(e);}

21
Output

7. Write a swing program to implement multiple mouse event.

22
Code

import javax.swing.*;

import java.awt.*;

import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

class Main {

private JFrame mainFrame;

private JLabel headerLabel;

private JLabel statusLabel;

private JPanel controlPanel;

public Main(){

prepareGUI();

public static void main(String[] args){

Main swingListenerDemo = new Main();

swingListenerDemo.showMouseListenerDemo();

private void prepareGUI(){

mainFrame = new JFrame("Java SWING Examples");

mainFrame.setSize(400,400);

mainFrame.setLayout(new GridLayout(3, 1));

headerLabel = new JLabel("",JLabel.CENTER );

23
statusLabel = new JLabel("",JLabel.CENTER);

statusLabel.setSize(350,100);

mainFrame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){

System.exit(0);

});

controlPanel = new JPanel();

controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);

mainFrame.add(controlPanel);

mainFrame.add(statusLabel);

mainFrame.setVisible(true);

private void showMouseListenerDemo(){

headerLabel.setText("Listener in action: MouseListener");

JPanel panel = new JPanel();

panel.setBackground(Color.magenta);

panel.setLayout(new FlowLayout());

panel.addMouseListener(new CustomMouseListener());

JLabel msglabel =

new JLabel("Welcome to Mouse Events .",JLabel.CENTER);

panel.add(msglabel);

24
msglabel.addMouseListener(new CustomMouseListener());

panel.add(msglabel);

controlPanel.add(panel);

mainFrame.setVisible(true);

class CustomMouseListener implements MouseListener {

public void mouseClicked(MouseEvent e) {

statusLabel.setText("Mouse Clicked: ("+e.getX()+", "+e.getY() +")");

public void mousePressed(MouseEvent e) {

statusLabel.setText("Mouse pressed: ("+e.getX()+", "+e.getY() +")");

public void mouseReleased(MouseEvent e) {

statusLabel.setText("Mouse released: ("+e.getX()+", "+e.getY() +")");

public void mouseEntered(MouseEvent e) {

statusLabel.setText("Mouse entered: ("+e.getX()+", "+e.getY() +")");

public void mouseExited(MouseEvent e) {

statusLabel.setText("Mouse exit: ("+e.getX()+", "+e.getY() +")");

25
8. Write a swing program to implement layout manager.

Border layout

Code

import java.awt.*;

import javax.swing.*;

class Border

JFrame f;

Border()

f = new JFrame();

// creating buttons

JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH

JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH

JButton b3 = new JButton("EAST");; // the button will be labeled as EAST

JButton b4 = new JButton("WEST");; // the button will be labeled as WEST

26
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER

f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction

f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction

f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction

f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction

f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center

f.setSize(300, 300);

f.setVisible(true);

public static void main(String[] args) {

new Border();

Output

9. Write a swing program to check login validation by using database.

Code.

Main.java file

27
package com.logintut;

import javax.swing.*;

import javax.swing.JOptionPane;

import java.awt.*;

import java.awt.event.*;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

class Myframe extends JFrame implements ActionListener{

JLabel labelName, labelEmail,labelFaculty,labelPassword;

JTextField t1,t2,t3,t4;

JButton submit , Login;

private String dbURL = "jdbc:mysql://localhost:3306/validation";

private String username = "root";

private String dbpassword = "";

private Connection conn;

String tabelName = "STUDENTS";

Myframe(){

setTitle("Register");

setSize(700,500);

setLocationRelativeTo(null);

setDefaultCloseOperation(EXIT_ON_CLOSE);

28
Container c = getContentPane();

c.setLayout(null);

labelName = new JLabel("name");

labelName.setBounds(20,50,100,20);

c.add(labelName);

t1=new JTextField();

t1.setBounds(130,50,100,20);

c.add(t1);

labelEmail = new JLabel("email");

labelEmail.setBounds(20,100,100,20);

c.add(labelEmail);

t2=new JTextField();

t2.setBounds(130,100,100,20);

c.add(t2);

labelFaculty = new JLabel("faculty");

labelFaculty.setBounds(20,150,100,20);

c.add(labelFaculty);

t3=new JTextField();

t3.setBounds(130,150,100,20);

c.add(t3);

labelPassword = new JLabel("password");

labelPassword.setBounds(20,200,100,20);

c.add(labelPassword);

29
t4=new JTextField();

t4.setBounds(130,200,100,20);

c.add(t4);

submit = new JButton("Submit");

submit.setBounds(150,350,80,20);

c.add(submit);

Login = new JButton("Login");

Login.setBounds(250,350,80,20);

c.add(Login);

submit.addActionListener(this);

Login.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

SignIn lg = new SignIn();

});

setVisible(true);

@Override

public void actionPerformed(ActionEvent e) {

String name = t1.getText();

String email = t2.getText();

30
String faculty = t3.getText();

String password = t4.getText();

String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

boolean check_email = email.matches(emailPattern);

if(name.isEmpty()|| name.isBlank()) {

JOptionPane.showMessageDialog(new JFrame(), "Please Enter Your Name");

return;

if(email.isEmpty() || email.isBlank()){

JOptionPane.showMessageDialog(new JFrame(), "Please Enter Your email");

return;

}else if(!check_email){

JOptionPane.showMessageDialog(new JFrame(), "Please Enter valid email

format");

return;

if(faculty.isBlank() || faculty.isEmpty()){

JOptionPane.showMessageDialog(new JFrame(), "Please Enter your faculty");

return;

if(password.isEmpty() || password.isBlank()){

JOptionPane.showMessageDialog(new JFrame(), "Please Enter your

password");

return;

31
}

try{

Class.forName("com.mysql.cj.jdbc.Driver");

conn = DriverManager.getConnection(dbURL,username,dbpassword);

if(conn !=null){

System.out.println("successfully connected");

}else System.out.println(" connection Failed");

String InsertQ ="INSERT INTO " + tabelName +

"(name,email,faculty,password)

VALUES('"+name+"','"+email+"','"+faculty+"','"+password+"')";

Statement insertTable = conn.createStatement();

insertTable.executeUpdate(InsertQ);

System.out.println("Inserted Successfully");

}catch(ClassNotFoundException ex){

ex.printStackTrace();

}catch (SQLException ex){

ex.printStackTrace();

public class Main {

public static void main(String[] args){

32
Myframe myframe = new Myframe();

SignIn.java file

package com.logintut;

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.sql.*;

public class SignIn extends JFrame {

JLabel labelEmail, labelPassword;

JTextField t1,t2;

JButton submit;

private String dbURL = "jdbc:mysql://localhost:3306/validation";

private String username = "root";

private String dbpassword = "";

private Connection conn;

String tabelName = "STUDENTS";

public SignIn(){

setTitle("Login");

setSize(700,500);

33
setLocationRelativeTo(null);

setDefaultCloseOperation(DISPOSE_ON_CLOSE);

Container c = getContentPane();

c.setLayout(null);

labelEmail = new JLabel("email");

labelEmail.setBounds(20,50,100,20);

c.add(labelEmail);

t1=new JTextField();

t1.setBounds(130,50,100,20);

c.add(t1);

labelPassword = new JLabel("password");

labelPassword.setBounds(20,100,100,20);

c.add(labelPassword);

t2=new JTextField();

t2.setBounds(130,100,100,20);

c.add(t2);

submit = new JButton("Login");

submit.setBounds(150,200,80,20);

c.add(submit);

setVisible(true);

submit.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

String email = t1.getText();

String password = t2.getText();

34
if(email.isEmpty() || email.isBlank()){

JOptionPane.showMessageDialog(new JFrame(), "Please Enter Your

email");

return;

if(password.isEmpty() || password.isBlank()){

JOptionPane.showMessageDialog(new JFrame(), "Please Enter your

password");

return;

try{

Class.forName("com.mysql.cj.jdbc.Driver");

conn = DriverManager.getConnection(dbURL,username,dbpassword);

if(conn !=null){

System.out.println("successfully connected");

}else System.out.println(" connection Failed");

Statement st = conn.createStatement();

String select = "select password from students where email =

'"+t1.getText()+"'";

ResultSet rs = st.executeQuery(select);

String get_password = "";

while (rs.next()){

get_password = rs.getString(1);

35
}

if(get_password.equals(t2.getText())){

JOptionPane.showMessageDialog(new JFrame(), "Login Success");

}else{

JOptionPane.showMessageDialog(new JFrame(), "email or password is

incorrect");

}catch(ClassNotFoundException ex){

ex.printStackTrace();

}catch (SQLException ex){

ex.printStackTrace();

});

Output

36
10. create distributed system using RMI.

Hello.java

import java.rmi.Remote;

import java.rmi.RemoteException;

// Creating Remote interface for our application

public interface Hello extends Remote {

void Add(Integer a,Integer b) throws RemoteException;

Developing the Implementation Class (Remote Object)

ImplExample.java

// Implementing the remote interface

public class ImplExample implements Hello {

ImplExample(){super();}

// Implementing the interface method

public void Add(Integer x, Integer y) {

37
System.out.println("Sum = " + (x+y));

ServerRMI.java

import java.rmi.registry.Registry;

import java.rmi.registry.LocateRegistry;

import java.rmi.RemoteException;

import java.rmi.server.UnicastRemoteObject;

public class Server extends ImplExample {

public Server() {}

public static void main(String args[]) {

try {

// Instantiating the implementation class

ImplExample obj = new ImplExample();

// Exporting the object of implementation class (here we are exporting the remote object

to the stub)

Hello skeleton = (Hello) UnicastRemoteObject.exportObject(obj, 0);

// Binding the remote object (stub) in the registry

Registry registry = LocateRegistry.getRegistry();

registry.bind("RMITest", skeleton);

System.err.println("Server ready");

} catch (Exception e) {

System.err.println("Server exception: " + e.toString());

e.printStackTrace();

38
}

ClientRMI.java

import java.rmi.registry.LocateRegistry;

import java.rmi.registry.Registry;

public class ClientRMI {

private ClientRMI() {}

public static void main(String[] args) {

try {

// A Java RMI registry is a simplified name service that allows clients to get a reference

(a stub) to a

remote object. In general, a registry is used (if at all) only to locate the first remote object

a client needs to

use.

// Getting the registry

Registry registry = LocateRegistry.getRegistry();

// Looking up the registry for the remote object

Hello stub = (Hello) registry.lookup("RMITest");

// Calling the remote method using the obtained object

stub.Add(5,10);

// System.out.println("Remote method invoked");

39
} catch (Exception e) {

System.err.println("Client exception: " + e.toString());

e.printStackTrace();

Output

40

You might also like