Showing posts with label JComboBox. Show all posts
Showing posts with label JComboBox. Show all posts

Tuesday, October 18, 2011

Retrieve Data From Database and Display Using JComboBox

Program Description:

The Java Program below is similar to the topic I created about retrieving data from database and display using JList, the only difference is that this program is using JComboBox instead of JList to display the retrieved data from MS Access Database. See "Important Part of the Program" below to compare and understand the whole java program easily.


Output:
Code:

/**
 * File: retrieveDBUsingJCB.java
 * Tiltle: Retrieve Data From Database and Display Using JComboBox
 * Author: http://java-program-sample.blogspot.com/
 */

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

Important Part of the Program:

//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");
    }
   }
  }
  );

Thursday, July 28, 2011

Add Item on JComboBox using JTextField

Output:
Code:

/**
 * File: jtextfieldToJComboBox.java
 * Tiltle: Add Item on JComboBox using JTextField
 * Author: http://java-program-sample.blogspot.com
 */
 
//Java Extension Packages
import javax.swing.*;
//Java Core Packages
import java.awt.*;
import java.awt.event.*;

public class jtextfieldToJComboBox extends JFrame {
 
 //Initializing JTextField and JComboBox
 private JComboBox combo;
 private JTextField input;

 //Setting up GUI
 public jtextfieldToJComboBox() {

 //Setting up the Title of the Window
 super("Add Item on JComboBox using JTextField");

 //Set Size of the Window (WIDTH, LENGTH)
 setSize(320,80);

 //Exit Property of the Window
 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 //Constructing JTextField and JComboBox
 input = new JTextField("Type your Input Here and Press Enter");
 combo = new JComboBox();

 //Setting JComboBox Properties
 combo.setMaximumRowCount(5); //Number of Itmes to be displayed. If greater than 5, Vertical ScrollBar will be displayed.

 //Setting up the container ready for the components to be added.
    Container pane = getContentPane();
    setContentPane(pane);
    
    //Setting up the container layout
 GridLayout layout = new GridLayout(2,1);
 pane.setLayout(layout);

 //Implemeting Even-Listener on JTextField's reference name "input" using ActionListener
 input.addActionListener(
  new ActionListener() {
   
   //Handle JTextField event if Enter key is pressed
   public void actionPerformed(ActionEvent event) {
    
    //Store the input from JTextField to the variable "message"
    String message = "The Input <"+input.getText()+"> is Successfully Added!";
    
    //Adding items or elements from JTextField to JComboBox
    combo.addItem(input.getText());
    
    //Display the input from JTextField to JOptionPane using the variable "message"
    JOptionPane.showMessageDialog(null, message,"Successfully Added!",JOptionPane.INFORMATION_MESSAGE);
    
    //The JTextField will be empty after JOptionPane is closed ready for the next input.
    input.setText(null);
   }
  }
  );

 //Adding JTextField and JComboBox in the container
 pane.add(input);
 pane.add(combo);
 
 /**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) {
  jtextfieldToJComboBox jtcb = new jtextfieldToJComboBox();
 }
}

Important Part of the Program:

//Implemeting Even-Listener on JTextField's reference name "input" using ActionListener
 input.addActionListener(
  new ActionListener() {
   
   //Handle JTextField event if Enter key is pressed
   public void actionPerformed(ActionEvent event) {
    
    //Store the input from JTextField to the variable "message"
    String message = "The Input <"+input.getText()+"> is Successfully Added!";
    
    //Adding items or elements from JTextField to JComboBox
    combo.addItem(input.getText());
    
    //Display the input from JTextField to JOptionPane using the variable "message"
    JOptionPane.showMessageDialog(null, message,"Successfully Added!",JOptionPane.INFORMATION_MESSAGE);
    
    //The JTextField will be empty after JOptionPane is closed ready for the next input.
    input.setText(null);
   }
  }
  );

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Hostgator Discount Code