Thursday 4 October 2012

creating a java sub-menu

This java program is used for creating a java sub-menu.

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;

public class creatingSubJMenuItem extends JFrame {

 //Initializing program components
 private JMenu menus;
 private JMenuBar bar;
 private JMenu mainItem[];
 private JMenuItem subItems[];

 //Setting up GUI
    public creatingSubJMenuItem() {
   
     //Setting up the Title of the Window
     super("Creating a Sub JMenuItem");

     //Set Size of the Window (WIDTH, HEIGHT)
     setSize(350,200);

     //Exit Property of the Window
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
  //Constructing JMenu "File" with mnemonic 'F'
     menus = new JMenu("File");
     menus.setMnemonic('F');
   
     //Constructing main JMenu and add it in JMenu "File"
     mainItem = new JMenu[1];
   
     for(int count=0; count<mainItem.length; count++){
      mainItem[count] = new JMenu("Main Menu "+(count+1));
      menus.add(mainItem[count]); //Adding JMenu "mainItem" in the JMenu "File"
     }
   
     //Constructing JMenuItem "subItems" as a Sub Menu to the main JMenu
     subItems = new JMenuItem[5];
   
     for(int count=0; count<subItems.length; count++){
      subItems[count] = new JMenuItem("Sub Menu "+(count+1));
      mainItem[0].add(subItems[count]); //Adding JMenuItem "subItems" in the JMenu "mainItem"
     }
   
     //Constructing JMenuBar
     bar = new JMenuBar();
     bar.add(menus); //Adding the JMenu "File" in the JMenuBar
   
     //Setting up the JMenuBar in the container
     setJMenuBar(bar);

     //Setting up the container ready for the components to be added.
     Container pane = getContentPane();
     setContentPane(pane);

     /**Set all the Components Visible.
      * If it is set to "false", the components in the container will not be visible.
      */
     setVisible(true);
    }
  
 //Main Method
    public static void main (String[] args) {
     creatingSubJMenuItem csjmi = new creatingSubJMenuItem();
 }
}






Wednesday 3 October 2012

Password demo in java

package javaapplication1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;

public class JavaApplication1 extends JPanel implements ActionListener{

    private static String OK = "ok";
    private static String HELP = "help";

    private JFrame controllingFrame; //needed for dialogs
    private JPasswordField passwordField;

    public JavaApplication1(JFrame f) {
        //Use the default FlowLayout.
        controllingFrame = f;

        //Create everything.
        passwordField = new JPasswordField(10);
        passwordField.setActionCommand(OK);
        passwordField.addActionListener(this);

        JLabel label = new JLabel("Enter the password: ");
        label.setLabelFor(passwordField);

        JComponent buttonPane = createButtonPanel();

        //Lay out everything.
        JPanel textPane = new JPanel(new FlowLayout(FlowLayout.TRAILING));
        textPane.add(label);
        textPane.add(passwordField);

        add(textPane);
        add(buttonPane);
    }

    protected JComponent createButtonPanel() {
        JPanel p = new JPanel(new GridLayout(0,1));
        JButton okButton = new JButton("OK");
        JButton helpButton = new JButton("Help");

        okButton.setActionCommand(OK);
        helpButton.setActionCommand(HELP);
        okButton.addActionListener(this);
        helpButton.addActionListener(this);

        p.add(okButton);
        p.add(helpButton);

        return p;
    }

    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();

        if (OK.equals(cmd)) { //Process the password.
            char[] input = passwordField.getPassword();
            if (isPasswordCorrect(input)) {
                JOptionPane.showMessageDialog(controllingFrame,
                    "Success! You typed the right password.");
            } else {
                JOptionPane.showMessageDialog(controllingFrame,
                    "Invalid password. Try again.",
                    "Error Message",
                    JOptionPane.ERROR_MESSAGE);
            }

            //Zero out the possible password, for security.
            Arrays.fill(input, '0');

            passwordField.selectAll();
            resetFocus();
        } else { //The user has asked for help.
            JOptionPane.showMessageDialog(controllingFrame,
                "You can get the password by searching this example's\n"
              + "source code for the string \"correctPassword\".\n"
              + "Or look at the section How to Use Password Fields in\n"
              + "the components section of The Java Tutorial.");
        }
    }

    /**
     * Checks the passed-in array against the correct password.
     * After this method returns, you should invoke eraseArray
     * on the passed-in array.
     */
    private static boolean isPasswordCorrect(char[] input) {
        boolean isCorrect = true;
        char[] correctPassword = { 'b', 'u', 'g', 'a', 'b', 'o', 'o' };

        if (input.length != correctPassword.length) {
            isCorrect = false;
        } else {
            isCorrect = Arrays.equals (input, correctPassword);
        }

        //Zero out the password.
        Arrays.fill(correctPassword,'0');

        return isCorrect;
    }

    //Must be called from the event dispatch thread.
    protected void resetFocus() {
        passwordField.requestFocusInWindow();
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("PasswordDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        final JavaApplication1 newContentPane = new JavaApplication1(frame);
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Make sure the focus goes to the right component
        //whenever the frame is initially given the focus.
        frame.addWindowListener(new WindowAdapter() {
            public void windowActivated(WindowEvent e) {
                newContentPane.resetFocus();
            }
        });

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                //Turn off metal's use of bold fonts
        UIManager.put("swing.boldMetal", Boolean.FALSE);
        createAndShowGUI();
            }
        });
    }
}

OUT PUT:
TYPE THE PASSWORD AS "bugaboo" AND PRESS OK BUTTON

Textfield demo in java

package javaapplication1;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JavaApplication1 extends JPanel implements ActionListener{

    protected JTextField textField;
    protected JTextArea textArea;
    private final static String newline = "\n";

    public JavaApplication1() {
        super(new GridBagLayout());

        textField = new JTextField(20);
        textField.addActionListener(this);

        textArea = new JTextArea(5, 20);
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textArea);

        //Add Components to this panel.
        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;

        c.fill = GridBagConstraints.HORIZONTAL;
        add(textField, c);

        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1.0;
        c.weighty = 1.0;
        add(scrollPane, c);
    }

    public void actionPerformed(ActionEvent evt) {
        String text = textField.getText();
        textArea.append(text + newline);
        textField.selectAll();

        //Make sure the new text is visible, even if there
        //was a selection in the text area.
        textArea.setCaretPosition(textArea.getDocument().getLength());
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("TextDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Add contents to the window.
        frame.add(new JavaApplication1());

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
    }




Saturday 29 September 2012

Retriving data using jcombo



CREATE A DATABASE  "addItemDB.mdb" IN MS-ACCESS.
CREATE A TABLE "persons" with the following fields
id- Auto Number
firstName-Text
middleName-Text
familyName-Text
Age- Number
SAVE THE DATABASE.

TYPE THE FOLLOWING CODE IN THE NOTEPAD AND RUN THE PROGRAM

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class retrieveDBUsingJCB extends JFrame {
   
    //Initializing program components
    private JButton buttons[];
    private JComboBox listBox;
    private JPanel p1,p2;
    private String bLabel[] = {"ID","First Name","Middle Name","Last Name","Age"};
   
    Connection con;
    Statement st;
    ResultSet rs;
    String db;

    //Setting up GUI
    public retrieveDBUsingJCB() {
       
        //Setting up the Title of the Window
        super("Retrieve DB and Display Using JComboBox");

        //Set Size of the Window (WIDTH, HEIGHT)
        setSize(300,200);

        //Exit Property of the Window
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               
        //Constructing JButtons and JComboBox
        buttons = new JButton[5];
        listBox = new JComboBox();
       
        //Setting up JComboBox property
        listBox.setMaximumRowCount(5);
       
        //Constructing JPanel 1 and its property
        p1 = new JPanel();
        p1.setBorder(BorderFactory.createTitledBorder("Database: "));
        p1.add(listBox); //Adding JComboBox in JPanel 1
       
        //Constructing JPanel 2 and its property
        p2 = new JPanel();
        p2.setLayout(new GridLayout(5,1));
        p2.setBorder(BorderFactory.createTitledBorder("Display: "));
       
        //Constructing all 5 JButtons using "for loop" and add it in JPanel 2
        for(int count=0; count<buttons.length; count++) {
            buttons[count] = new JButton(bLabel[count]);
            p2.add(buttons[count]);
        }
       
        //Setting up the container ready for the components to be added.
        Container pane = getContentPane();
        setContentPane(pane);

        //Setting up the container layout
        GridLayout grid = new GridLayout(1,2);
        pane.setLayout(grid);
       
        //Creating a connection to MS Access and fetch errors using "try-catch" to check if it is successfully connected or not.
        try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=addItemDB.mdb;";
                con = DriverManager.getConnection(db,"","");
                st = con.createStatement();
               
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE);
                System.exit(0);
            }
           
        //Implemeting Even-Listener on JButton buttons[0] which is ID
        buttons[0].addActionListener(
        new ActionListener() {
           
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                try {
                    listBox.removeAllItems();
                    //SQL for selecting the table "person" in the Database
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        //Displaying the field "id" from the table "person" in JComboBox
                        listBox.addItem(rs.getString("id"));
                    }
                   
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
       
        //Implemeting Even-Listener on JButton buttons[1] which is First Name
        buttons[1].addActionListener(
        new ActionListener() {
           
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                try {
                    listBox.removeAllItems();
                    //SQL for selecting the table "person" in the Database
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        //Displaying the field "firstName" from the table "person" in JComboBox
                        listBox.addItem(rs.getString("firstName"));
                    }
                   
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
       
        //Implemeting Even-Listener on JButton buttons[2] which is Middle Name
        buttons[2].addActionListener(
        new ActionListener() {
           
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                try {
                    listBox.removeAllItems();
                    //SQL for selecting the table "person" in the Database
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        //Displaying the field "middleName" from the table "person" in JComboBox
                        listBox.addItem(rs.getString("middleName"));
                    }
                   
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
       
        //Implemeting Even-Listener on JButton buttons[3] which is Last Name
        buttons[3].addActionListener(
        new ActionListener() {
           
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                try {
                    listBox.removeAllItems();
                    //SQL for selecting the table "person" in the Database
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        //Displaying the field "lastName" from the table "person" in JComboBox
                        listBox.addItem(rs.getString("familyName"));
                    }
                   
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
       
        //Implemeting Even-Listener on JButton buttons[4] which is Age
        buttons[4].addActionListener(
        new ActionListener() {
           
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                try {
                    listBox.removeAllItems();
                    //SQL for selecting the table "person" in the Database
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        //Displaying the field "age" from the table "person" in JComboBox
                        listBox.addItem(rs.getString("age"));
                    }
                   
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
                
        //Adding components to the container
        pane.add(p1);
        pane.add(p2);
       
        /**Set all the Components Visible.
         * If it is set to "false", the components in the container will not be visible.
         */
        setVisible(true);
        setResizable(false);
    }
   
    //Main Method
    public static void main (String[] args) {
        retrieveDBUsingJCB rdjcb = new retrieveDBUsingJCB();
    }
}

Friday 28 September 2012

Retriving data from the database



CREATE A DATABASE  "addItemDB.mdb" IN MS-ACCESS.
CREATE A TABLE "persons" with the following fields
id- Auto Number
firstName-Text
middleName-Text
familyName-Text
Age- Number
SAVE THE DATABASE.

TYPE THE FOLLOWING CODE IN THE NOTEPAD AND RUN THE PROGRAM




//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class retrieveDBUsingJList extends JFrame {
  
    //Initializing program components
    private DefaultListModel model;
    private JButton buttons[];
    private JList dbList;
    private JPanel p1,p2;
    private String bLabel[] = {"ID","First Name","Middle Name","Last Name","Age"};
  
    Connection con;
    Statement st;
    ResultSet rs;
    String db;

    //Setting up GUI
    public retrieveDBUsingJList() {
      
        //Setting up the Title of the Window
        super("Retrieve DB and Display Using JList");

        //Set Size of the Window (WIDTH, HEIGHT)
        setSize(300,200);

        //Exit Property of the Window
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              
        //Constructing JButtons, JList, and DefaultListModel
        model = new DefaultListModel();
        buttons = new JButton[5];
        dbList = new JList(model);
      
        //Setting up JList property
        dbList.setVisibleRowCount(5);
        dbList.setFixedCellHeight(27);
        dbList.setFixedCellWidth(130);
        dbList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      
        //Constructing JPanel 1 and its property
        p1 = new JPanel();
        p1.setBorder(BorderFactory.createTitledBorder("Database: "));
        p1.add(new JScrollPane(dbList)); //Adding JList in JPanel 1
      
        //Constructing JPanel 2 and its property
        p2 = new JPanel();
        p2.setLayout(new GridLayout(5,1));
        p2.setBorder(BorderFactory.createTitledBorder("Display: "));
      
        //Constructing all 5 JButtons using "for loop" and add it in JPanel 2
        for(int count=0; count<buttons.length; count++) {
            buttons[count] = new JButton(bLabel[count]);
            p2.add(buttons[count]);
        }
      
        //Setting up the container ready for the components to be added.
        Container pane = getContentPane();
        setContentPane(pane);

        //Setting up the container layout
        GridLayout grid = new GridLayout(1,2);
        pane.setLayout(grid);
      
        //Creating a connection to MS Access and fetch errors using "try-catch" to check if it is successfully connected or not.
        try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=addItemDB.mdb;";
                con = DriverManager.getConnection(db,"","");
                st = con.createStatement();      
              
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE);
                System.exit(0);
            }
          
        //Implemeting Even-Listener on JButton buttons[0] which is ID
        buttons[0].addActionListener(
        new ActionListener() {
          
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                try {
                    model.clear();
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        model.addElement(rs.getString("id"));
                    }
                  
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
      
        //Implemeting Even-Listener on JButton buttons[1] which is First Name
        buttons[1].addActionListener(
        new ActionListener() {
          
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                    try {
                    model.clear();
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        model.addElement(rs.getString("firstName"));
                    }
                  
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
      
        //Implemeting Even-Listener on JButton buttons[2] which is Middle Name
        buttons[2].addActionListener(
        new ActionListener() {
          
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                    try {
                    model.clear();
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        model.addElement(rs.getString("middleName"));
                    }
                  
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
      
        //Implemeting Even-Listener on JButton buttons[3] which is Last Name
        buttons[3].addActionListener(
        new ActionListener() {
          
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                    try {
                    model.clear();
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        model.addElement(rs.getString("familyName"));
                    }
                  
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
      
        //Implemeting Even-Listener on JButton buttons[4] which is Age
        buttons[4].addActionListener(
        new ActionListener() {
          
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                    try {
                    model.clear();
                    rs=st.executeQuery("select * from person");
                    while (rs.next()) {
                        model.addElement(rs.getString("age"));
                    }
                  
                } catch (Exception e) {
                    System.out.println("Retrieving Data Fail");
                }
            }
        }
        );
               
        //Adding components to the container
        pane.add(p1);
        pane.add(p2);
      
        /**Set all the Components Visible.
         * If it is set to "false", the components in the container will not be visible.
         */
        setVisible(true);
        setResizable(false);
    }
  
    //Main Method
    public static void main (String[] args) {
        retrieveDBUsingJList rdjl = new retrieveDBUsingJList();
    }
}

Thursday 27 September 2012

Java program to add information to ms-access



 CREATE A DATABASE  "addItemDB.mdb" IN MS-ACCESS.
CREATE A TABLE "persons" with the following fields
id- Auto Number
firstName-Text
middleName-Text
familyName-Text
Age- Number
SAVE THE DATABASE.


TYPE THE FOLLOWING CODE IN THE NOTEPAD AND RUN THE PROGRAM

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class addItemToDatabase extends JFrame {
   
    //Initializing Components
    private JTextField inputs[];
    private JButton add, reset;
    private JLabel labels[];
    private String fldLabel[] = {"First Name: ","Middle Name: ","Family Name: ","Age: "};
    private JPanel p1;
   
    Connection con;
    Statement st;
    ResultSet rs;
    String db;

    //Setting up GUI
    public addItemToDatabase() {
       
        //Setting up the Title of the Window
        super("Adding Data to the Database");

        //Set Size of the Window (WIDTH, HEIGHT)
        setSize(300,180);

        //Exit Property of the Window
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
        //Constructing Components
        inputs = new JTextField[4];
        labels = new JLabel[4];
        add = new JButton("Add");
        reset = new JButton("Reset");
        p1 = new JPanel();
       
        //Setting Layout on JPanel 1 with 5 rows and 2 column
        p1.setLayout(new GridLayout(5,2));

        //Setting up the container ready for the components to be added.
        Container pane = getContentPane();
        setContentPane(pane);

        //Setting up the container layout
        GridLayout grid = new GridLayout(1,1,0,0);
        pane.setLayout(grid);
       
        //Creating a connection to MS Access and fetching errors using "try-catch" to check if it is successfully connected or not.
        try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=addItemDB.mdb;";
                con = DriverManager.getConnection(db,"","");
                st = con.createStatement();       
               
                JOptionPane.showMessageDialog(null,"Successfully Connected to Database","Confirmation", JOptionPane.INFORMATION_MESSAGE);
               
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.ERROR_MESSAGE);
                System.exit(0);
            }
       
        //Constructing JLabel and JTextField using "for loop" in their desired order
        for(int count=0; count<inputs.length && count<labels.length; count++) {
            labels[count] = new JLabel(fldLabel[count]);
            inputs[count] = new JTextField(20);
           
            //Adding the JLabel and the JTextFied in JPanel 1
            p1.add(labels[count]);
            p1.add(inputs[count]);
        }
       
        //Implemeting Even-Listener on JButton add
        add.addActionListener(
        new ActionListener() {
           
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
               
                if (inputs[0].getText().equals("") || inputs[1].getText().equals("") || inputs[2].getText().equals("") || inputs[0].getText() == null || inputs[1].getText() == null || inputs[2].getText() == null)
                    JOptionPane.showMessageDialog(null,"Fill up all the Fields","Error Input", JOptionPane.ERROR_MESSAGE);
                   
                else
                   
                try {
                   
                    String add = "insert into person (firstName,middleName,familyName,age) values ('"+inputs[0].getText()+"','"+inputs[1].getText()+"','"+inputs[2].getText()+"',"+inputs[3].getText()+")";
                    st.execute(add); //Execute the add sql
                   
                    Integer.parseInt(inputs[3].getText()); //Convert JTextField Age in to INTEGER
                   
                    JOptionPane.showMessageDialog(null,"Item Successfully Added","Confirmation", JOptionPane.INFORMATION_MESSAGE);
                   
                }catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(null,"Please enter an integer on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
                }catch (Exception ei) {
                    JOptionPane.showMessageDialog(null,"Failure to Add Item. Please Enter a number on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
        );
       
        //Implemeting Even-Listener on JButton reset
        reset.addActionListener(
        new ActionListener() {
           
            //Handle JButton event if it is clicked
            public void actionPerformed(ActionEvent event) {
                inputs[0].setText(null);
                inputs[1].setText(null);
                inputs[2].setText(null);
                inputs[3].setText(null);
            }
        }
        );
       
        //Adding JButton "add" and "reset" to JPanel 1 after the JLabel and JTextField
        p1.add(add);
        p1.add(reset);
       
        //Adding JPanel 1 to the container
        pane.add(p1);
       
        /**Set all the Components Visible.
         * If it is set to "false", the components in the container will not be visible.
         */
        setVisible(true);
    }
   
    //Main Method
    public static void main (String[] args) {
        addItemToDatabase aid = new addItemToDatabase();
    }
}

Wednesday 26 September 2012

Simple Programs

   1. Welcome to java
class Hello
{
public static void main(String args[])
{
System.out.println("Welcome to java ");
}
}
output
 javac Hello.java
java Hello
Welcome to java


  2. To find the big number
class Big
{
public static void main(String args[])
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
if(a>b)
System.out.println("given number a is big" +a);
else
System.out.println("given number b is big" +b);
}
}
Output:
javac Big.java
java Big 12 32
given number b is big 32


  3. Operators
class Sum
{
public static void main(String args[])
{
int a=65;
int b=47;
int c=a+b;
int d=a-b;
int e=a*b;
System.out.println("sum given numbers a & b " +c);
System.out.println("difference of given numbers a & b" +d);
System.out.println("multiplication of given numbers a & b" +e);
}
}
Output:
javac Sum.java
java Sum
Sum of given numbers a & b 112
Difference of given numbers a & b 18
Multiplication of given numbers a & b 3055


4. Even or odd
class Evenodd
{
public static void main(String args[])
{
int a=Integer.parseInt(args[0]);
if(a%2==0)
System.out.println("given number a is even" +a);
else
System.out.println("given number a is odd" +a);
}
}
 Output:
javac Evenodd.java
java Evenodd 2
Given number a is even2


5. factorial and its average
class Factorial
{
public  static void main(String args[])
{
int fact=1;
int n=Integer.parseInt(args[0]);
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("factorial of given number is "+sum);
double avg=sum/n;
System.out.println("Average of factorial is "+avg);
}
}
Output
javac Factorial.java
java Factorial 5
factorial of given number is 120
average of factorial is 24.0


6. Fibonacci Series
class Fibonacci
{
public static void main(String args[])
{
int n=Integer.parseInt(args[0]);
int next,f=0,s=1;
System.out.println(+f);
System.out.println(+s);
for (int i=1;i<=(n-2);i++)
{
next=f+s;
System.out.println(+next);
f=s;
s=next;
}
}
}
output:
javac Fibonacci.java
java Fibonacci 7
0
1
1
2
3
5
7.    print triangle with ‘*’

class Triangle
{
public static void main(String args[])
{
loop1:for(int i=0;i<=100;i++)
{
System.out.println();
if(i>10) break;
for(int j=0;j<=100;j++)
{
System.out.print("*");
if(i==j) continue loop1;
}
}
}
}
Out put:
javac Triangle.java
java Triangle
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
*  * * * * * * * *

8.  Palindrome or not
import java.io.*;
class Palindrome
{
public static void main(String args[])
{
try
{
BufferedReader object=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number");
int num=Integer.parseInt(object.readLine());
int n=num;
int rev=0;
System.out.println("Number:");
System.out.println(""+num);
for(int i=0;i<=num;i++)
{
int r=num%10;
num=num/10;
rev=rev*10+r;
i=0;
}
System.out.println("After reversing the number:"+"");
System.out.println(""+rev);
if(n==rev)
{
System.out.println("Number is palindrome");
}
else
{
System.out.println("number is not palindrome");
}
}
catch(Exception e)
{
System.out.println("out of range");
}
}
}
Output:
javac Palindrome.java
java Palindrome
Enter the number    1221
After reversing number
1221
Given number is Palindrome
 
9. find area using multiple class
class Room
{
float length;
float breath;
void getdata(float l, float b)
{
length=l;
breath=b;
}
}
class Roomarea
{
public static void main(String args[])
{
float area;
Room room1=new Room();
room1.getdata(14,10);
area=room1.length*room1.breath;
System.out.println("Area :" +area);
}
}
Output:
javac Roomarea.java
java Roomarea
Area =140.0


10.        print transpose of given matrix
import java.io.*;
class Trans
{
public static void main(String args[]) throws IOException
{
int a[][]=new int[5][5];
int i,j;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter how many row and columns for matrix A");
int m=Integer.parseInt(br.readLine());
int n=Integer.parseInt(br.readLine());
System.out.println("enter the elements into matrix ");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("Given matrix is .....");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.print("\t" +a[i][j]);
}
System.out.println();
}
System.out.println("Transpose of given matrix is .....");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.print("\t" +a[j][i]);
}
System.out.println();
}
}
}


Output:
Javac Trans.java
Java Trans
Enter how many rows and columns in matrix A:
2
2
Enter the elements into matrix A:
1
2
3
4
Given matrix is ….
1      2
3      4
Transpose of given matrix is….
1        3
2      4


11.    Matrix Addition
import java.io.*;
class Addition
{
public static void main(String args[]) throws IOException
{
int a[][]=new int[5][5];
int b[][]=new int[5][5];
int c[][]=new int[5][5];
int i,j;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter how many row and columns for matrix A");
int m=Integer.parseInt(br.readLine());
int n=Integer.parseInt(br.readLine());
System.out.println("enter the elements into matrix A");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("Enter how many row and columns for matrix B");
int p=Integer.parseInt(br.readLine());
int q=Integer.parseInt(br.readLine());
System.out.println("enter the elements into matrix B");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
b[i][j]=Integer.parseInt(br.readLine());
}
}
if(m!=p&&n!=q)
{
System.out.println("Addition not  possible");
System.exit(0);
}
else
for(i=0;i<m;i++)
{
System.out.println();
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
System.out.println("result matrix is .....");
for(i=0;i<m;i++)
{
System.out.println();
for(j=0;j<n;j++)
{
System.out.print("\t" +c[i][j]);
}
}
}
}    


Output:
javac Addition.java
java Addition
Enter how many rows and columns for matrix A:
2
2
Enter the elements into matrix A:
1
2
3
4
Enter how many rows and columns for matrix B:
2
2
Enter elements into matrix B:
1
2
3
4
Result matrix is….
2               4
6               8              


                                                                  
12.      Matrix multiplication.
import java.io.*;
class Multiplication
{
public static void main(String args[]) throws IOException
{
int a[][]=new int[5][5];
int b[][]=new int[5][5];
int c[][]=new int[5][5];
int i,j;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter how many row and columns for matrix A");
int m=Integer.parseInt(br.readLine());
int n=Integer.parseInt(br.readLine());
System.out.println("enter the elements into matrix A");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("Enter how many row and columns for matrix B");
int p=Integer.parseInt(br.readLine());
int q=Integer.parseInt(br.readLine());
System.out.println("enter the elements into matrix B");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
b[i][j]=Integer.parseInt(br.readLine());
}
}
if(m!=p&&n!=q)
{
System.out.println("Addition not  possible");
System.exit(0);
}
else
for(i=0;i<m;i++)
{
System.out.println();
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
System.out.println("result matrix is .....");
for(i=0;i<m;i++)
{
System.out.println();
for(j=0;j<n;j++)
{
System.out.print("\t" +c[i][j]);
}
}
}
}


Output:
javac Matrix.java
java Matrix
Enter how many rows and columns for matrix A:
2
2
Enter the elements into matrix A:
1
2
3
4
Enter how many rows and columns for matrix B:
2
2
Enter elements into matrix B:
5
6
7
8
Result matrix is….
6               8
10             12              


13. find complex number using constructors
class complex
{
int real,img;
complex() {}
complex(int a)
{
real=img=a;
}
complex(int x, int y)
{
real=x;
img=y;
}
complex sum(complex c1, complex c2)
{
complex c3=new complex();
c3.real=c1.real+c2.real;
c3.img=c1.img+c2.img;
return c3;
}
void display()
{
System.out.println(real+"+i"+img);
}
}
class Complexnum
{
public static void main(String args[])
{
complex c1=new complex(1,2);
complex c2=new complex(2);
complex c3=new complex();
c3=c3.sum(c1,c2);
c3.display();
}
}
Output:
Javac Complexnum.java
Java Complexnum
3+i4


14. find concatenation of two strings
class Concat
{
public static void main(String args[])
{
String str1="Table";
String str2="Tennis";
String Game=str1+" "+str2;
System.out.println(Game);
}
}
Output:
Javac Concat.java
Java Concat
Tabie tennis
                 
               


15.  bubble sort
import java.io.*;
class Bubblesort
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=0,i,j,t;
int a[]=new int[10];
System.out.println("Enter size of the array:");
try
{
n=Integer.parseInt(br.readLine());
}
catch(Exception e) {}
System.out.println("Enter elements into the array:");
try
{
for(i=0;i<n;i++)
a[i]=Integer.parseInt(br.readLine());
}
catch(Exception e) {}
for(i=0;i<n-1;i++)
for(j=0;j<n-1-i;j++)
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
System.out.println("The sorted array is:");
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}
Output:
javac Bubblesort.java
java Bubblesort
Enter the size of array
5
Enter the elements into the array
45
34
76
12
69
The sorted array is
12 34 45 69 76


16. selection sort
import java.io.*;
class Selectionsort
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=0,i,j,t;
int a[]=new int[10];
System.out.println("Enter size of the array:");
try
{
n=Integer.parseInt(br.readLine());
}
catch(Exception e){}
System.out.println("Enter elements into the array:");
try
{
for(i=0;i<n;i++)
a[i]=Integer.parseInt(br.readLine());
}
catch(Exception e){}
i=0;
while(i<n-1)
{
int key=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[key])
{
key=j;
}
}
t=a[key];
a[key]=a[i];
a[i]=t;
i++;
}
System.out.println("The sorted array is:");
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}


Output:
javac Selectionsort.java
java Selectionsort
Enter the size of array
5
Enter the elements into the array
45
34
76
12
69
The sorted array is
76 69 45 34 12


17.  Binary Search
import java.lang.*;
import java.util.*;
import java.io.*;
class Search
{
public int binarysearch(int[]a,int key)
{
int f=1;
int low=0;
int high=a.length-1;
int mid=(low+high)/2;
while(low<=high)
{
if(a[mid]==key)
{
f=0;
break;
}
if(a[mid]<key)
low=mid+1;
else
high=mid-1;
mid=(low+high)/2;
}
return(f);
}
}
class Binarysearch
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Search s=new Search();
int[]a;
int i,k,n;
int f=1;
System.out.println("Binary search");
System.out.println("enter your choice");
System.out.println("Enter the size of array");
n=sc.nextInt( );
a=new int[n];
System.out.println("Enter the elements");
for(i=0;i<n;i++)
a[i]=sc.next();
System.out.println("Enter the element to search:");
k=sc.nextInt();
int c=s.binarysearch(a,k);
if(c==0)
System.out.println("The element is found");
else
System.out.println("The elements is not found");
}
}


Output:
javac Binarysearch.java
java Binarysearch
BINARY SEARCH
Enter your choice
Enter the size of array
5
Enter the elements into the array
2
4
1
8
9
Enter the element to search
8
The element is found
Output:
javac Binarysearch.java
java Binarysearch
BINARY SEARCH
Enter your choice
Enter the size of array
5
Enter the elements into the array
2
4
1
8
9
Enter the element to search
10
The element not found

18.  Linear search
import java.lang.*;
import java.util.*;
import java.io.*;
class Search
{
public int linearsearch(int[]a,int key)
{
int flag=1;
for(int i=0;i<a.length;i++)
{
if(a[i]==key)
{
flag=0;
}
}
return(flag);
}
}
class Linearsearch
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
{
Search s=new Search( );
int []a;
int i,k,n,ch;
int f=1;
System.out.println("Linear Search\n");
System.out.println("Enter the size of array");
n=sc.nextInt( );
a=new int[n];
System.out.println("enter the elements");
for (i=0;i<n;i++)
a[i]=sc.nextInt( );
System.out.println("enter the element to search");
k=sc.nextInt( );
f=s.linearsearch(a,k);
if(f==0)
System.out.println("The element is found");
else
System.out.println("Element is not found");
}
}
}


Output:
javac Linearsearch.java
java Linearsearch
LINEAR SEARCH
Enter your choice
Enter the size of array
5
Enter the elements into the array
2
4
1
8
9
Enter the element to search
8
The element is found
Output:
javac Linearsearch.java
java Linearsearch
LINEAR SEARCH
Enter your choice
Enter the size of array
5
Enter the elements into the array
2
4
1
8
9
Enter the element to search
10
The element not found