You are on page 1of 68

PRACTICAL -1

1.Develop a swing application with different layouts


import javax.swing.*; import java.awt.*; public class differentlayout extends JFrame{ public differentlayout() { JFrame fr=new JFrame("This is main frame"); fr.setLayout(new GridLayout(2,2,2,2)); fr.setSize(200, 200); fr.setVisible(true); JPanel pn1=new JPanel(new GridLayout(4,1,2,2)); JPanel pn2=new JPanel(new FlowLayout(FlowLayout.TRAILING)); JPanel pn3=new JPanel(new BorderLayout()); JPanel pn4=new JPanel(); // pn4.setLayout(new BoxLayout(pn4,BoxLayout.Y_AXIS)); // pn4.add(Box.createRigidArea(new Dimension(0,5))); fr.add(pn1); fr.add(pn2); fr.add(pn3); fr.add(pn4); JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16; b1=new JButton("1"); b2=new JButton("2"); b3=new JButton("3"); b4=new JButton("4"); b5=new JButton("5"); b6=new JButton("6"); b7=new JButton("7"); b8=new JButton("8"); b9=new JButton("9"); b10=new JButton("10"); b11=new JButton("11"); b12=new JButton("12"); b13=new JButton("13"); b14=new JButton("14"); b15=new JButton("15"); b16=new JButton("16"); pn1.add(b1); pn1.add(b2); pn1.add(b3);

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:-

2.Create a menu-based application using Swing, which opens a


File Dialog box and allows user to select a file from local hard drives. Display name of a file selected into textbox. import javax.swing.*; import java.applet.*; import java.awt.*; import java.awt.event.*; public class menuItems extends JFrame{ menuItems(){ final JTextArea jta=new JTextArea(); add(jta); JMenu fileMenu = new JMenu( "File" ); JMenuItem NEW = new JMenuItem( "NEW" ); JMenuItem open = new JMenuItem( "OPEN" ); JMenuItem save = new JMenuItem( "SAVE" ); JMenuItem saveas = new JMenuItem( "SAVE AS" ); fileMenu.add(NEW); fileMenu.add(open); fileMenu.add(save); fileMenu.add(saveas); open.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { FileDialog fd = new FileDialog(new JFrame(), "Open Dialog"); fd.getDirectory(); fd.setVisible(true); jta.setText(fd.getFile()); } }); JMenuBar bar = new JMenuBar(); setJMenuBar( bar ); bar.add( fileMenu ); } public static void main(String args[]) { menuItems menuFrame = new menuItems(); // create MenuFrame menuFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); menuFrame.setSize( 500, 200 ); // set frame size menuFrame.setVisible( true ); } }

O/P:-

3.Write a java application that will change the color of a circle


from one color to another when the circle is clicked but will not change the color of the circle if somewhere else is clicked. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class circlecolor extends JApplet implements ActionListener,MouseListener { JPanel opp=new JPanel(); JButton b = new JButton("Draw Circle"); String msg; int x,y; int temp=0; Color c; public void init() { setSize(250, 250); add(opp,BorderLayout.NORTH); opp.setLayout(new FlowLayout(FlowLayout.CENTER)); opp.add(b); b.addActionListener(this); addMouseListener(this); } public void paint(Graphics g) { int R = (int)(255*Math.random()); int G = (int)(255*Math.random()); int B = (int)(255*Math.random()); c=new Color(R,G,B); if (temp==1) { g.setColor(c); g.fillOval(100, 100, 100, 100); } if(temp==0) { g.setColor(null); g.drawOval(100, 100, 100, 100); } showStatus(msg); } public void actionPerformed(ActionEvent e) { String s=e.getActionCommand(); if(s=="Draw Circle") {

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:-

4.Write a java application to display the following messages for


the matching mouse events Mouse Pressed, Mouse Released , Mouse Clicked, Mouse Entered, Mouse Exited. Also change the color of background for every event import import import import java.awt.*; java.awt.event.*; java.applet.*; javax.swing.*;

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:-

6.Write a java application that draws various figure as selected


from radio buttons. The radio buttons label displays the name of figure. Put one check box when it is checked it fills the figure with color. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class drawshaps extends JApplet implements ActionListener { JPanel opp=new JPanel(); ButtonGroup bg = new ButtonGroup(); JRadioButton rectangle=new JRadioButton("Rectangle"); JRadioButton circle=new JRadioButton("Circle"); JRadioButton sqare=new JRadioButton("Square"); JCheckBox Color=new JCheckBox("Color"); String msg; int sch=0; int cch=0; Color c; public void init() { setSize(250, 250); add(opp,BorderLayout.WEST); opp.setLayout(new GridLayout(4,1)); bg.add(rectangle); bg.add(sqare); bg.add(circle); opp.add(rectangle); opp.add(sqare); opp.add(circle); opp.add(Color); rectangle.addActionListener(this); circle.addActionListener(this); sqare.addActionListener(this); Color.addActionListener(this); } public void paint(Graphics g) { switch (sch) { case 1:

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:-

7.Write a java application that can add, subtract, multiply, divide


two numbers. Use text fields, buttons and labels for creating interface. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class uicalc implements ActionListener { JFrame f=new JFrame("This The UI Calc..."); JPanel pm=new JPanel(); JPanel pn=new JPanel(); JPanel pn1=new JPanel(); JPanel pn2=new JPanel(); JPanel pb=new JPanel(); JPanel pa=new JPanel(); static static static static static static static static static static static JButton JButton JButton JButton bp=new JButton("+"); bs=new JButton("-"); bm=new JButton("*"); bd=new JButton("/");

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:-

8.Develop an user interface that perform the following SQL


operations: (i) Select Delete import import import import java.awt.*; java.awt.event.*; java.sql.*; javax.swing.*; (ii) Insert (iii) Update (iv)

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:-

9.Write a java application that finds out no. of records, no. of


columns and types of columns within a table. import com.sun.org.apache.regexp.internal.*; import java.sql.*; public class tabledetail { public static void main(String[] args) { int count = 0; try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:DNS"); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select * from contactdetail"); while(rs.next()) { count+=1; } ResultSetMetaData rsmd = rs.getMetaData(); int noc=rsmd.getColumnCount(); System.out.println(" TABLE DETAIL"); System.out.println("Number of Record : "+count); System.out.println("Number of Column : "+noc); System.out.println(" COLUMN DETAIL"); System.out.println(" --------------"); System.out.println("NAME\tTYPE"); for (int i = 1; i <= noc; i++) { String col_name = rsmd.getColumnName(i); System.out.println(col_name +"\t"+rsmd.getColum nTypeName(i)); } } catch(Exception e) { System.out.println("Exception Occur "); } } }

O/P:TABLE DETAIL Number of Record : 2 Number of Column : 2 COLUMN DETAIL -------------NAME TYPE uname VARCHAR unumber VARCHAR

10.Write a java application that verifies the user login.


import import import import import java.awt.*; java.awt.event.*; javax.swing.*; com.sun.org.apache.regexp.internal.*; java.sql.*;

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:-

11.Write an applet that contains one button called Calculate


Salary. When you click the button a new window will open for calculating salary. Take input like basic salary, DA%, HRA% etc and show total salary calculated. Create a new class for second window. import import import import import import import import import java.awt.FlowLayout; java.awt.GridLayout; java.awt.event.ActionEvent; java.awt.event.ActionListener; javax.swing.JButton; javax.swing.JFrame; javax.swing.JLabel; javax.swing.JPanel; javax.swing.JTextField;

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:-

12.Create a simple calculator using various panels of flow layout,


grid layout and Borderlayout. import import import import java.awt.*; javax.swing.*; java.awt.event.*; javax.swing.event.*;

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

1.Create a Java application that demonstrates the implementation of Java Beans.


ResultBean.java package beans; publicclassResultBeanimplementsjava.io.Serializable { private String name; privatebooleanresult; privateintm; /* No-arg constructor.... */ publicResultBean(){ } public String getName() { returnthis.name; } publicvoidsetName(final String name) { this.name = name; } publicvoidsetMarks(int m) { this.m =m; } publicbooleanisPass() { if(m>35) returnthis.result=true; else returnthis.result=false; } } TestBean.java importbeans.ResultBean; publicclassTestBean { publicstaticvoid main(String[] args) { ResultBean person = newResultBean(); person.setName("Vikram"); person.setMarks(80); System.out.print(person.getName()+ " is : "); System.out.println(person.isPass()? "Pass" : "Fail");

} } 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(); }

catch (Exception e) {} } } O/P:From Server : Hello Client Your Random No Is : 48

5. Modified Program4 provide the Client applet in place of Simple Client.


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 =""+((int)(Math.random()*1000)%100); ps.println(str); ps.close(); ss.close(); s.close(); } } Client.java importjava.awt.*; import java.io.*; import java.net.*; importjavax.swing.*; class Client extendsJFrame { publicstaticvoid main(String args[ ]) throws Exception { JFrame f=newJFrame(); f.setVisible(true); f.setSize(200, 100); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); JPanel p=newJPanel(); f.add(p); JLabel l=newJLabel("Your Random No.:"); JTextField t=newJTextField(5); p.add(l); p.add(t);

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:-

6. Write a java application that implements the


chatting. Programs, client and server, have two text areas to display the message send from the program.
Server.java import java.net.*; importjavax.swing.*; import java.io.*; importjava.awt.*; importjava.awt.event.*; classserverextendsJFrameimplementsActionListener { ServerSocketservSoc = null; Socket soc=null; DataInputStreamdin=null; PrintWriterpr = null; JPanelpanel1=newJPanel(); JButtonbutton1=newJButton("Send"); JTextAreatext1=newJTextArea(50,20); JTextAreatext2=newJTextArea(5,30); classreadMsgimplements Runnable { Thread t=null; readMsg() { t=newThread(this); t.start(); } publicvoid run() { while(true) { try { text1.setText(text1.getText() +din.readLine()); } catch(Exception e){} } } }

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()); }

} publicstaticvoid main(String args[]) throws Exception { serverserver1=new server(); } }

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:-

7. Write a java RMI application which implements the simple


arithmetic operations like add, multiply, subtract and divide. The client program sends two data and the arithmetic operation it wants to perform. The server performs the operation and sends back the result to the client. Calc.java: (interface) importjava.rmi.*;

public interface Calc extends Remote { intcalci(intx,inty,char op) throws RemoteException; }

Calcser.java(Server) importjava.rmi.*; importjava.rmi.server.*;

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()); } } }

Calcal.java (client) import java.net.*; importjava.rmi.*; importjava.rmi.server.*; importjava.util.*; import java.io.*;

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)

{ System.out.println("Ans is : "+ans); } else { System.out.println("Enter valid data"); } } catch(Exception ee) { System.out.println("Error"+ee.getMessage()); } } }

O/P:Registration:

Client:

You might also like