Practical 1
Practical 1
Practical 1
pn1.add(b4); pn2.add(b5); pn2.add(b6); pn2.add(b7); pn2.add(b8); pn3.add(b9,BorderLayout.CENTER); pn3.add(b10,BorderLayout.SOUTH); pn3.add(b11,BorderLayout.EAST); pn3.add(b12,BorderLayout.WEST); pn4.add(b13); pn4.add(b14); pn4.add(b15); pn4.add(b16); fr.setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String[] args) { differentlayout dl=new differentlayout(); } }
O/P:-
O/P:-
msg="Circle Is Here..."; repaint(); } } public void mouseClicked(MouseEvent e) { x=e.getX(); y=e.getY(); if((x>100 && x<200)) { if(y>100 && y<200) { temp=1; msg="Clicked Inside Circle..."; } } if((x<100 || x>200)) { if(y<100 || y>200) { temp=0; msg="Clicked Out of Circle..."; } } repaint(); } public {} public {} public {} public {} } void mousePressed(MouseEvent e) void mouseReleased(MouseEvent e) void mouseEntered(MouseEvent arg0) void mouseExited(MouseEvent arg0)
O/P:-
public class mousecolor extends JApplet implements MouseListener { String msg=""; int x=100,y=100; int color=0; JPanel pnl=new JPanel(); public void init() { add(pnl); pnl.addMouseListener(this); } public void paint(Graphics g) { switch (color) { case 0: pnl.setBackground(Color.RED); break; case 1: pnl.setBackground(Color.CYAN); break; case 2: pnl.setBackground(Color.DARK_GRAY); break; case 3: pnl.setBackground(Color.GREEN); break; case 4: pnl.setBackground(Color.BLUE); break; case 5: pnl.setBackground(Color.magenta); break; } showStatus(msg); } public void mouseClicked(java.awt.event.MouseEvent arg0) {
msg="Mouse Clicked..."; color=1; repaint(); } public void mouseEntered(java.awt.event.MouseEvent arg0) { msg="Mouse Enterd..."; color=2; repaint(); } public void mouseExited(java.awt.event.MouseEvent arg0) { msg="Mouse Exited..."; color=3; repaint(); } public void mousePressed(java.awt.event.MouseEvent arg0) { msg="Mouse Pressed..."; color=4; repaint(); } public void mouseReleased(java.awt.event.MouseEvent arg0) { msg="Mouse Released..."; color=5; repaint(); } }
O/P:-
5.Write a java application that moves a circle up, down, left, right
using arrow key. The circle can also drag using mouse. import import import import import import javax.swing.*; java.awt.*; java.awt.event.KeyEvent; java.awt.event.KeyListener; java.awt.event.MouseEvent; java.awt.event.MouseMotionListener;
class movecircle extends JFrame { int x=0; int y=0; Circle circle; movecircle() { super("Moving Circle "); setSize(300,300); setVisible(true); addMouseMotionListener(new CircleMouseListener()); addKeyListener(new CircleKeyListener()); circle=new Circle(); add(circle); } class Circle extends JComponent { public void paintComponent(Graphics g) { super.paintComponent(g); getContentPane().setBackground(Color.magenta); g.setColor(Color.white); g.drawOval(x, y,50,50); } } class CircleMouseListener implements MouseMotionListener { public void mouseDragged(MouseEvent e) { x = e.getX(); y = e.getY(); repaint(); } public void mouseMoved(MouseEvent e)
{ } } class CircleKeyListener implements KeyListener { public void keyPressed(KeyEvent ke) { if (ke.getKeyCode() == KeyEvent.VK_UP) { y=y-5; } else if (ke.getKeyCode() == KeyEvent.VK_DOWN) { y=y+5; } else if (ke.getKeyCode() == KeyEvent.VK_LEFT) { x=x-5; } else if (ke.getKeyCode() == KeyEvent.VK_RIGHT) { x=x+5; } repaint(); } public void keyReleased(KeyEvent arg0) { } public void keyTyped(KeyEvent arg0) { } } public static void main(String[] args) { movecircle mcircle = new movecircle(); } }
O/P:-
if(cch==1) { g.setColor(c.CYAN); g.fillRect(100, 75, 100, 50); } else g.drawRect(100, 75, 100, 50); break; case 2: if(cch==1) { g.setColor(c.CYAN); g.fillOval(100, 75, 100, 100); } else g.drawOval(100, 75, 100, 100); break; case 3: if(cch==1) { g.setColor(c.CYAN); g.fillRect(100, 75, 100, 100); } else g.drawRect(100, 75, 100, 100); break; } showStatus(msg); } public void actionPerformed(ActionEvent e) { String s=e.getActionCommand(); if(s=="Color") { cch=1; repaint(); } else { cch=0; repaint(); } if(s=="Rectangle") { sch=1; cch=0; msg="Circle selected"; repaint();
} if(s=="Circle") { sch=2; cch=0; msg="Circle selected"; repaint(); } if(s=="Square") { sch=3; cch=0; msg="Square selected"; repaint(); } } }
O/P:-
JLabel no1=new JLabel("No.1 :"); JLabel no2=new JLabel("No.2 :"); JLabel ans=new JLabel("ANSWER :"); JLabel wc=new JLabel("::WELCOME::"); JTextField n1=new JTextField(25); JTextField n2=new JTextField(25); JTextField answer=new JTextField(25);
uicalc() { f.setSize(350, 300); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setVisible(true); f.setLayout(new GridLayout(4,1,2,2)); f.add(pm); f.add(pn); f.add(pb); f.add(pa); pm.setLayout(new FlowLayout(FlowLayout.CENTER)); pm.add(wc); pn.setLayout(new GridLayout(2,1,2,2)); pn.add(pn1); pn.add(pn2); pn1.setLayout(new FlowLayout(FlowLayout.CENTER)); pn2.setLayout(new FlowLayout(FlowLayout.CENTER));
pn1.add(no1); pn1.add(n1); pn2.add(no2); pn2.add(n2); pb.setLayout(new FlowLayout(FlowLayout.CENTER)); pb.add(bp); pb.add(bs); pb.add(bm); pb.add(bd); pa.setLayout(new FlowLayout(FlowLayout.CENTER)); pa.add(ans); pa.add(answer); bp.addActionListener(this); bs.addActionListener(this); bm.addActionListener(this); bd.addActionListener(this); } public static void main(String[] args) { uicalc c=new uicalc(); } public void actionPerformed(ActionEvent e) { if(n1.getText().equals("")| n1.getText().equals("")) { JLabel errorFields = new JLabel("<HTML><FONT COLOR = Purple>Enter Both Value....</FONT></HTML>"); JOptionPane.showMessageDialog(null,errorFields); n1.requestFocus(); } else { double num1=Double.parseDouble(n1.getText()); double num2=Double.parseDouble(n2.getText()); double answ; if (e.getActionCommand()=="+") { answ=num1+num2; answer.setText(""); answer.setText(answer.getText()+answ); } if (e.getActionCommand()=="-") { answ=num1-num2; answer.setText(""); answer.setText(answer.getText()+answ); }
if (e.getActionCommand()=="*") { answ=num1*num2; answer.setText(""); answer.setText(answer.getText()+answ); } if (e.getActionCommand()=="/") { try { if(num2==0) { n2.setText(""); JLabel errorFields = new JLabel("<HTML><FONT COLOR = Red>IN Division Denominator must Not Equal To 0...</FONT></HTML>"); JOptionPane.showMessageDialog(null,errorFields); n2.requestFocus(); } else { answ=num1/num2; answer.setText(""); answer.setText(answer.getText()+answ); } } catch(Exception ex) { JLabel errorFields = new JLabel("<HTML><FONT COLOR = Red>"+ex.getMessage() +"</FONT></HTML>"); JOptionPane.showMessageDialog(null,errorFields); } } } } }
O/P:-
public class sqlstatement implements ActionListener { static static static static static static static static static static static static static static JFrame f=new JFrame("This is The Main Frame..."); JPanel pnll=new JPanel(); JPanel pnlf=new JPanel(); JPanel pnlb=new JPanel(); JLabel ml=new JLabel(" :: WELCOME ::"); JLabel namel=new JLabel("Name :"); JLabel numberl=new JLabel("Number :"); JTextField name=new JTextField(25); JTextField number=new JTextField(25); JButton insb=new JButton("INSERT"); JButton updtb=new JButton("UPDATE"); JButton dltb=new JButton("DELETE"); JButton slctb=new JButton("SHOW"); JButton exit=new JButton("EXIT");
sqlstatement() { f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setSize(400, 250); f.setVisible(true); f.setLayout(new GridLayout(3,1,2,2)); f.add(pnll); f.add(pnlf); f.add(pnlb); pnll.setLayout(new FlowLayout(FlowLayout.CENTER)); pnll.add(ml); pnlf.setLayout(new GridLayout(2,2,10,10)); pnlf.add(namel,BorderLayout.WEST); pnlf.add(name); pnlf.add(numberl); pnlf.add(number); pnlb.setLayout(new FlowLayout(FlowLayout.CENTER)); pnlb.add(insb); pnlb.add(updtb);
pnlb.add(dltb); pnlb.add(slctb); pnlb.add(exit); insb.addActionListener(this); updtb.addActionListener(this); dltb.addActionListener(this); slctb.addActionListener(this); exit.addActionListener(this); } public void actionPerformed(ActionEvent e) { String s=e.getActionCommand(); String uname=name.getText(); String unumber; if(uname == "") { JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>Please Insert Some Data ... </FONT></HTML>"); JOptionPane.showMessageDialog(null,errorFields); } try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connectioncon=DriverManager.getConnection("jd bc:odbc:DNS"); if(s=="INSERT") { unumber=number.getText(); PreparedStatement pstmt=con.prepareStatement("insert into cont actdetail values(?,?)"); pstmt.setString(1, uname); pstmt.setString(2, unumber); pstmt.executeUpdate(); name.setText(""); number.setText(""); JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>DATA Insert Successfully for name :"+uname+" <BR> Number :"+unumber+"... </FONT></HTML>"); errorFields.setSize(125,50); JOptionPane.showMessageDialog(null,errorFields); }
if(s=="UPDATE" && uname !="") { unumber=number.getText(); Statement stmt=con.createStatement(); boolean rs=stmt.execute("UPDATE contactdetail SET unumber='"+unumber+"' WHERE uname="+uname+""); JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>DATA Updated Successfully for name :"+uname+" <BR> Number :"+unumber+"... </FONT></HTML>"); JOptionPane.showMessageDialog(null,errorFields); } if(s=="DELETE" && uname !="") { Statement stmt=con.createStatement(); int rs=stmt.executeUpdate("DELETE * FROM contactdetail WHERE uname='"+uname+"'"); name.setText(""); number.setText(""); JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>DATA Deleted Successfully...</FONT></HTML >"); JOptionPane.showMessageDialog(null,errorFields); } if(s=="SHOW" && uname !="") { Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("SELECT * FROM contactdetail WHERE uname='"+uname+"'"); while(rs.next()) { JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>Number of "+uname+" Is :"+rs.getString(2)+"... </FONT></HTML>"); JOptionPane.showMessageDialog(null,errorFields); }
name.setText(""); number.setText(""); } if(s=="EXIT") { System.exit(0); } } catch (ClassNotFoundException ex) { JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>"+ex+"</FONT></ HTML>"); JOptionPane.showMessageDialog(null,errorFields); } catch (SQLException ex) { JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>"+ex+"</FONT></ HTML>"); JOptionPane.showMessageDialog(null,errorFields); } } public static void main(String[] args) { sqlstatement st=new sqlstatement(); } }
O/P:-
O/P:TABLE DETAIL Number of Record : 2 Number of Column : 2 COLUMN DETAIL -------------NAME TYPE uname VARCHAR unumber VARCHAR
public class login extends JFrame { private JLabel jLabel1; private JLabel jLabel2; private JTextField jTextField1; private JPasswordField jPasswordField1; private JButton jButton1; private JPanel contentPane; public login() { super(); create(); this.setVisible(true); } private void create() { jLabel1 = new JLabel(); jLabel2 = new JLabel(); jTextField1 = new JTextField(); jPasswordField1 = new JPasswordField(); jButton1 = new JButton(); contentPane = (JPanel)this.getContentPane(); jLabel1.setHorizontalAlignment(SwingConstants.LEFT); jLabel1.setForeground(new Color(0, 0, 5)); jLabel1.setText("username:"); jLabel2.setHorizontalAlignment(SwingConstants.LEFT); jLabel2.setForeground(new Color(0, 0, 5)); jLabel2.setText("password:"); jTextField1.setForeground(new Color(0, 0, 255)); jTextField1.setSelectedTextColor(new Color(0, 0, 255)); jTextField1.setToolTipText("Enter your username"); jPasswordField1.setForeground(new Color(0, 0, 255)); jPasswordField1.setToolTipText("Enter your password");
jButton1.setBackground(new Color(200, 200, 200)); jButton1.setForeground(new Color(0, 0, 5)); jButton1.setText("Login"); jButton1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jButton1_actionPerformed(e); } }); contentPane.setLayout(null); contentPane.setBorder(BorderFactory.createEtchedBorder()); contentPane.setBackground(new Color(204, 204, 204)); addComponent(contentPane, jLabel1, 5,10,106,18); addComponent(contentPane, jLabel2, 5,47,97,18); addComponent(contentPane, jTextField1, 110,10,183,22); addComponent(contentPane, jPasswordField1, 110,45,183,22); addComponent(contentPane, jButton1, 150,75,83,28); this.setTitle("Login To Members Area"); this.setLocation(new Point(76, 182)); this.setSize(new Dimension(335, 141)); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setResizable(false); } // Add Component Without a Layout Manager (Absolute Positioning) private void addComponent(Container container,Component c,int x,int y,int width,int height) { c.setBounds(x,y,width,height); container.add(c); } private void jButton1_actionPerformed(ActionEvent e) { String username = new String(jTextField1.getText()); String password = new String(jPasswordField1.getText()); if(username.equals("") || password.equals("")) { jButton1.setEnabled(false); JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>You must enter a username and password to login...</FONT></HTML>"); JOptionPane.showMessageDialog(null,errorFields); jTextField1.setText("");
jPasswordField1.setText(""); jButton1.setEnabled(true); this.setVisible(true); } else { try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:DNS"); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("SELECT password FROM login WHERE name='"+username+"'"); while(rs.next()) { if(rs.getString(1).equals(password)) { JLabel optionLabel = new JLabel("<HTML><FONT COLOR = Blue>MR./Mrs. </FONT><FONT COLOR = RED> <B>"+username+"</B></FONT> <FONT COLOR = Blue> You Logged In successfully...</ FONT></HTML>"); JOptionPane.showMessageDialog(null, optionLabel); } else { JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>Incorrect name or Password...</FONT></HTML>"); JOptionPane.showMessageDialog(null,errorFields); } } } catch(Exception ex) { JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>Exception Occur....</FONT></HTML>"); JOptionPane.showMessageDialog(null,errorFields);
} } } public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLo okAndFeel"); } catch (Exception ex) { System.out.println("Failed loading L&F: "); System.out.println(ex); } new login(); }; }
O/P:-
public class salary extends JFrame implements ActionListener { salary() { super("Calculate Salary"); setVisible(true); setSize(200,200); setLayout(new FlowLayout()); JButton cs=new JButton("Calculate Salary"); add(cs); cs.addActionListener(this); } public static void main(String[] args) { salary sr=new salary(); } public void actionPerformed(ActionEvent ae) { show s=new show(); } } class show extends JFrame implements ActionListener { JLabel ans; JTextField bst; JTextField dat; JTextField hrat;
show() { super("Enter Value:"); setVisible(true); setSize(400,200); setLayout(new FlowLayout()); JPanel p=new JPanel(); JButton cs=new JButton("Calculate"); JLabel bs=new JLabel("Basic Salary:"); JLabel DA=new JLabel("DA%"); JLabel HRA=new JLabel("HRA%:"); ans=new JLabel(""); bst=new JTextField(15); dat=new JTextField(15); hrat=new JTextField(15); p.setLayout(new GridLayout(3,3)); p.add(bs); p.add(bst); p.add(DA); p.add(dat); p.add(HRA); p.add(hrat); add(p); add(cs); add(ans); cs.addActionListener(this); } public void actionPerformed(ActionEvent arg0) { double total,bs,da,hra; bs=Double.parseDouble(bst.getText()); da=Double.parseDouble(dat.getText()); hra=Double.parseDouble(hrat.getText()); total=bs-(bs*da*0.01)-(bs*hra*0.01); ans.setText("Total Salary:"+Double.toString(total)); } }
O/P:-
public class cal extends JFrame implements ActionListener { JTextField tfield; double temp, temp1, result, a; int k = 1, x = 0, y = 0, z = 0; char ch; JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, zero,plus, min, div, mul, eq,dot; Container cont; JPanel textPanel, buttonpanel; cal() { cont = getContentPane(); cont.setLayout(new BorderLayout()); JPanel textpanel = new JPanel(); tfield = new JTextField(25); tfield.setHorizontalAlignment(SwingConstants.RIGHT); tfield.addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent keyevent) { char c = keyevent.getKeyChar(); if (c >= '0' && c <= '9') { } else { keyevent.consume(); } } }); textpanel.add(tfield); buttonpanel = new JPanel(); buttonpanel.setLayout(new GridLayout(4, 4, 2, 2)); boolean t = true; b1 = new JButton("1"); buttonpanel.add(b1); b1.addActionListener(this); b2 = new JButton("2"); buttonpanel.add(b2); b2.addActionListener(this); b3 = new JButton("3"); buttonpanel.add(b3);
b3.addActionListener(this); plus = new JButton("+"); buttonpanel.add(plus); plus.addActionListener(this); b4 = new JButton("4"); buttonpanel.add(b4); b4.addActionListener(this); b5 = new JButton("5"); buttonpanel.add(b5); b5.addActionListener(this); b6 = new JButton("6"); buttonpanel.add(b6); b6.addActionListener(this); min = new JButton("-"); buttonpanel.add(min); min.addActionListener(this); b7 = new JButton("7"); buttonpanel.add(b7); b7.addActionListener(this); b8 = new JButton("8"); buttonpanel.add(b8); b8.addActionListener(this); b9 = new JButton("9"); buttonpanel.add(b9); b9.addActionListener(this); mul = new JButton("*"); buttonpanel.add(mul); mul.addActionListener(this); dot = new JButton("."); buttonpanel.add(dot); dot.addActionListener(this); zero = new JButton("0"); buttonpanel.add(zero); zero.addActionListener(this); eq = new JButton("="); buttonpanel.add(eq); eq.addActionListener(this); div = new JButton("/"); div.addActionListener(this); buttonpanel.add(div); cont.add("Center", buttonpanel); cont.add("North", textpanel); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals("1")) {
if (z == 0) { tfield.setText(tfield.getText() + "1"); } else { tfield.setText(""); tfield.setText(tfield.getText() + "1"); z = 0; } } if (s.equals("2")) { if (z == 0) { tfield.setText(tfield.getText() } else { tfield.setText(""); tfield.setText(tfield.getText() z = 0; } } if (s.equals("3")) { if (z == 0) { tfield.setText(tfield.getText() } else { tfield.setText(""); tfield.setText(tfield.getText() z = 0; } } if (s.equals("4")) { if (z == 0) { tfield.setText(tfield.getText() } else { tfield.setText(""); tfield.setText(tfield.getText() z = 0; } } if (s.equals("5")) { if (z == 0) { tfield.setText(tfield.getText() } else { tfield.setText(""); tfield.setText(tfield.getText() z = 0; } } if (s.equals("6")) { if (z == 0) { tfield.setText(tfield.getText() } else { tfield.setText("");
+ "2"); + "2");
+ "3"); + "3");
+ "4"); + "4");
+ "5"); + "5");
+ "6");
tfield.setText(tfield.getText() + "6"); z = 0; } } if (s.equals("7")) { if (z == 0) { tfield.setText(tfield.getText() } else { tfield.setText(""); tfield.setText(tfield.getText() z = 0; } } if (s.equals("8")) { if (z == 0) { tfield.setText(tfield.getText() } else { tfield.setText(""); tfield.setText(tfield.getText() z = 0; } } if (s.equals("9")) { if (z == 0) { tfield.setText(tfield.getText() } else { tfield.setText(""); tfield.setText(tfield.getText() z = 0; } } if (s.equals("0")) { if (z == 0) { tfield.setText(tfield.getText() } else { tfield.setText(""); tfield.setText(tfield.getText() z = 0; } } if (s.equals("AC")) { tfield.setText(""); x = 0; y = 0; z = 0; } if (s.equals(".")) { if (y == 0) { tfield.setText(tfield.getText()
+ "7"); + "7");
+ "8"); + "8");
+ "9"); + "9");
+ "0"); + "0");
+ ".");
y = 1; } else { tfield.setText(tfield.getText()); } } if (s.equals("+")) { if (tfield.getText().equals("")) { tfield.setText(""); temp = 0; ch = '+'; } else { temp = Double.parseDouble(tfield.getText()); tfield.setText(""); ch = '+'; y = 0; x = 0; } tfield.requestFocus(); } if (s.equals("-")) { if (tfield.getText().equals("")) { tfield.setText(""); temp = 0; ch = '-'; } else { x = 0; y = 0; temp = Double.parseDouble(tfield.getText()); tfield.setText(""); ch = '-'; } tfield.requestFocus(); } if (s.equals("/")) { if (tfield.getText().equals("")) { tfield.setText(""); temp = 1; ch = '/'; } else { x = 0; y = 0; temp = Double.parseDouble(tfield.getText()); ch = '/'; tfield.setText(""); } tfield.requestFocus(); } if (s.equals("*")) { if (tfield.getText().equals("")) {
tfield.setText(""); temp = 1; ch = '*'; } else { x = 0; y = 0; temp = Double.parseDouble(tfield.getText()); ch = '*'; tfield.setText(""); } tfield.requestFocus(); } if (s.equals("=")) { if (tfield.getText().equals("")) { tfield.setText(""); } else { temp1 = Double.parseDouble(tfield.getText()); switch (ch) { case '+': result = temp + temp1; break; case '-': result = temp - temp1; break; case '/': result = temp / temp1; break; case '*': result = temp * temp1; break; } tfield.setText(""); tfield.setText(tfield.getText() +result); z = 1; } } tfield.requestFocus(); }
public static void main(String args[]) { cal f = new cal(); f.setTitle("Calculator"); f.pack(); f.setVisible(true);
} }
O/P:-
PRACTICAL -2
} } O/P:Vikram is : Pass
2.Create a Java application which retrieves the Host Name when IP address is given and vice-versa.
AddIP.java import java.io.*; import java.net.*; publicclassAddIP { publicstaticvoid main(String[] ar) throwsIOException { BufferedReaderbr = newBufferedReader(new InputStreamReader(System.in)); System.out.print("Enter a website name: "); String site = br.readLine(); System.out.println("IP Address is :"+InetAddress.getByName(site).getHostAddress()); System.out.println("IP Address is :"+InetAddress.getByName(site).getHostName()); } } O/P:Enter a website name: www.yahoo.com IP Address is :98.137.149.56 IP Address is :www.yahoo.com
3.Modified the above program and provide the facility to retrieve Local Port, Local Name, and Local Host etc.
Localinfo.java importjava.io.IOException; import java.net.*; publicclasslocalinfo { publicstaticvoid main(String[] arg) throwsIOException { try { Socket s=newSocket("localhost",80); InetAddressaddr= s.getLocalAddress(); System.out.println("Local Port is : "+s.getLocalPort()); System.out.println("Local Host Name is : "+addr.getLocalHost().getHostName()); System.out.println("Local Host Address is : "+addr.getLocalHost().getHostAddress()); s.close(); } catch (UnknownHostException e) { System.out.println(e.getMessage()); } } } O/P:Local Port is : 1072 Local Host Name is :Vicky-PC Local Host Address is : 127.0.0.1
4. Develop a java application in which a server program returns a random number between 0 to 100 whenever java client connect to it.
Server.java import java.io.*; import java.net.*; class Server { publicstaticvoid main(String args[ ]) throws Exception { ServerSocketss = newServerSocket(777); Socket s = ss.accept(); OutputStreamobj = s.getOutputStream(); PrintStreamps = newPrintStream(obj); String str = "Hello Client Your Random No Is : "+((int)(Math.random()*1000)%100); ps.println(str); ps.close(); ss.close(); s.close(); } } Client.java import java.io.*; import java.net.*; class Client extendsJFrame { publicstaticvoid main(String args[ ]) throws Exception { try{ Socket s = newSocket("localhost", 777); InputStreamobj = s.getInputStream(); BufferedReaderbr = newBufferedReader(new InputStreamReader(obj)); String str; while((str = br.readLine()) != null) System.out.println("From Server :\n"+str); br.close(); s.close(); }
try{ Socket s = newSocket("localhost", 777); InputStreamobj = s.getInputStream(); BufferedReaderbr = newBufferedReader(new InputStreamReader(obj)); String str; while((str = br.readLine()) != null) t.setText(str); br.close(); s.close(); } catch (Exception e) {} } } O/P:-
server() { super("Server"); try { servSoc=newServerSocket(2008); panel1.setLayout(null); setLayout(newBorderLayout()); text1.setBounds(5,5,400,200); text2.setBounds(5,210,400,50); button1.setBounds(5,290,200,50); text1.setEditable(false); text1.setForeground(Color.BLUE); text2.setForeground(Color.MAGENTA); panel1.add(text1); panel1.add(text2); panel1.add(button1); getContentPane().add(panel1); setSize(250,250); setVisible(true); button1.addActionListener(this); try{ UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLo okAndFeel"); SwingUtilities.updateComponentTreeUI(panel1); } catch(Exception e){} soc=servSoc.accept(); din= newDataInputStream(soc.getInputStream()); pr=newPrintWriter(soc.getOutputStream(),true); readMsgr=newreadMsg(); } catch(Exception e){} } publicvoidactionPerformed(ActionEventae) { System.out.println("Chat Start ..."); if(ae.getActionCommand().equals("Send")) { pr.println("Server: "+text2.getText()); text1.setText(text1.getText()+ "\nServer: "+text2.getText()); }
Client.java import java.net.*; importjavax.swing.*; import java.io.*; importjava.awt.*; importjava.awt.event.*; classclientextendsJFrameimplementsActionListener { Socket soc=null; PrintWriterpr=null; DataInputStreamdin =null; JPanelpanel1=newJPanel(); JButtonbutton1=newJButton("Send"); JTextAreatext1=newJTextArea(50,20); JTextAreatext2=newJTextArea(5,30); classmsgsimplements Runnable { Thread t=null; msgs() { t=newThread(this); t.start(); } publicvoid run() { while(true) { try { text1.setText(text1.getText() +din.readLine()); } catch(Exception ae){} } } } client() { try {
soc=new Socket("localhost",2008); din= newDataInputStream(soc.getInputStream()); pr=newPrintWriter(soc.getOutputStream(),true); panel1.setLayout(null); setName("Client"); setLayout(newBorderLayout()); text1.setBounds(5,5,400,200); text2.setBounds(5,210,400,50); text1.setEditable(false); text1.setForeground(Color.BLUE); text2.setForeground(Color.MAGENTA); button1.setBounds(5,290,200,50); panel1.add(text1); panel1.add(text2); panel1.add(button1); getContentPane().add(panel1); button1.addActionListener(this); try{ UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLo okAndFeel"); SwingUtilities.updateComponentTreeUI(panel1); } catch(Exception e){} msgsm = newmsgs(); } catch(Exception e){} } publicvoidactionPerformed(ActionEventae) { if(ae.getActionCommand().equals("Send")) { pr.println("Client: "+text2.getText()); text1.setText(text1.getText()+ "\nClient: "+text2.getText()); text2.setText(""); } } publicstaticvoid main(String args[]) { client client1=new client(); client1.setSize(500,400); client1.setVisible(true); } } O/P:-
public class Calcser extends UnicastRemoteObject implements Calc { publicCalcser()throws RemoteException {} publicintcalci(intx,inty,char op) { char c; c=op; switch(op) { case '+':
returnx+y; //break; case '-': return x-y; //break; case '*': return x*y; //break; case '/': if(y!=0) { return x/y; } else { return -1; } //break; default: return -1; } } } Regi.java (Registration in rmi registry) import java.net.*; importjava.rmi.*; importjava.rmi.server.*;
classRegi { public static void main(String st[]) { Calcsercs=null; try { cs=new Calcser(); Naming.rebind("call",cs); } catch(Exception ee) { System.out.println(error+ee.getMessage()); } } }
classCalcal { public static void main(String st[]) { Calccq=null; Scanner sc=new Scanner(System.in); String url="rmi://localhost/call"; try { cq=(Calc)Naming.lookup(url); System.out.println("Enter 1st no :"); int a=Integer.parseInt(sc.next()); System.out.println("Enter 2nd no :"); int b=Integer.parseInt(sc.next()); System.out.println("Enter operator :"); String c1=sc.next(); char c=c1.charAt(0); intans=cq.calci(a,b,c); if(ans!=-1)
O/P:Registration:
Client: