Friday, 29 July 2016

Java program to add information to ms-access

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

Retrieving data from the database

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

Retriving data using jcombo

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

Text field demo in java

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

Password Demo in java

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

Creating a Java Menu

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