Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 10-27-2009, 03:28 AM   PM User | #1
jbodary
New to the CF scene

 
Join Date: Oct 2009
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
jbodary is an unknown quantity at this point
combobox not loading info from array

Trying to load info from a database into an array and then into a combobox.
This is what I have so far - in interest of readability I took out the code that pertained to the other buttons and such on the form, whats left is just the jbombo code and the code that gets the info from the database.

Code:
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;


public class billingInfoUI extends javax.swing.JFrame {

    public billingInfoUI() {
        initComponents();
    }

    @SuppressWarnings("unchecked")

    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        hoursWorked = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        flatRate = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        workType = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jComboBox1.setModel(new DefaultComboBoxModel(customers));



public class CustomerData {

	//database url "test" is the database name
	private static final String JDBC_CONNECTION_URL	= "jdbc:mysql://localhost/test";

	//database username
	private static final String DATABASE_USER 		= "root";
	//database password
	private static final String DATABASE_PASSWORD	= "root";


	// query to select customer data
	private static final String SQL_FETCH_CUSTOMERS = "SELECT custName FROM customers";

	private Connection connection = null;


	public CustomerData(){
		// setup database connection
		initConnection();
	}

	/**
	 * create database connection
	 */
	private void initConnection() {
		try {
			//load the mysql driver
			Class.forName("com.mysql.jdbc.Driver");
			//create the database connection
			connection = DriverManager.getConnection(JDBC_CONNECTION_URL, DATABASE_USER, DATABASE_PASSWORD);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public void closeConnection(){
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				connection = null;
			}
		}
	}


	public ArrayList fetchCustomerData(){
		if (connection != null){
			Statement statement = null;
			try {
				statement = connection.createStatement();
				//get results from database
				ResultSet resultSet = statement.executeQuery(SQL_FETCH_CUSTOMERS);
				//get customers from resultset and return them to the app
				return convertResultSetToCustomersArray(resultSet);
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				//close the statement we just used
				if (statement != null){
					try {
						statement.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		}else{
			System.out.println("NO VALID DATABASE CONNECTION, CAN'T FETCH CUSTOMER DATA!");
		}
		// if we reach this point, something went wrong, so return empty list
		return new ArrayList();
	}

	public ArrayList convertResultSetToCustomersArray(ResultSet results) throws SQLException{
		ArrayList customers = new ArrayList();

		//loop the results and add customers to an ArrayList
		while (results.next()){
			customers.add(results.getString("custName"));
		}
		return customers;
	}
        public String[] customers = null;
        public void initData(){
		CustomerData customerData = new CustomerData();

		ArrayList custArrayList = customerData.fetchCustomerData();

		//get the array from the ArrayList and cast it to a String[]
		customers = (String[]) custArrayList.toArray(new String[0]);
	}
}




    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new billingInfoUI().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify
    private javax.swing.JTextField flatRate;
    private javax.swing.JTextField hoursWorked;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JList workType;
    // End of variables declaration

}
jbodary is offline   Reply With Quote
Old 10-27-2009, 04:20 AM   PM User | #2
sn3twork
New to the CF scene

 
Join Date: Oct 2009
Posts: 9
Thanks: 0
Thanked 0 Times in 0 Posts
sn3twork is an unknown quantity at this point
Hmm, are you setting the DefaultComboBoxModel before there is data in customers[]?

Last edited by sn3twork; 10-27-2009 at 04:22 AM..
sn3twork is offline   Reply With Quote
Old 10-27-2009, 04:31 AM   PM User | #3
jbodary
New to the CF scene

 
Join Date: Oct 2009
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
jbodary is an unknown quantity at this point
I think I am calling something to early, because now I am getting a null exception I just cant figure out what I am putting in the wrong order-- this is my code in its entirety minus the extra gui code for the other buttons on the form

Code:
package my.freelancebillingapp;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;



public class billingInfoUI extends javax.swing.JFrame {
        public String[] customers = null;


    public billingInfoUI() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        hoursWorked = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        flatRate = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        workType = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jComboBox1.setModel(new DefaultComboBoxModel(customers));

    }// </editor-fold>

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    }                                        

    private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {                                      
        new FreelanceBillingUI().setVisible(true);
        setVisible(false);
    }                                     

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      
String hoursWorkedtxt = hoursWorked.getText();
String flatRatetxt = flatRate.getText();
workType.getSelectedValue();
workType.toString();
Object workTypetxt = workType.getSelectedValue();

if(hoursWorkedtxt.contains("H")){
hoursWorkedtxt = "0";
}else{
flatRatetxt = "0";
}

    }                                     

public class CustomerData {

	//database url "test" is the database name
	private static final String JDBC_CONNECTION_URL	= "jdbc:mysql://localhost/test";

	//database username
	private static final String DATABASE_USER 		= "root";
	//database password
	private static final String DATABASE_PASSWORD	= "root";


	// query to select customer data
	private static final String SQL_FETCH_CUSTOMERS = "SELECT custName FROM customers";

	private Connection connection = null;


	public CustomerData(){
		// setup database connection
		initConnection();
	}

	/**
	 * create database connection
	 */
	private void initConnection() {
		try {
			//load the mysql driver
			Class.forName("com.mysql.jdbc.Driver");
			//create the database connection
			connection = DriverManager.getConnection(JDBC_CONNECTION_URL, DATABASE_USER, DATABASE_PASSWORD);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public void closeConnection(){
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				connection = null;
			}
		}
	}


	public ArrayList fetchCustomerData(){
		if (connection != null){
			Statement statement = null;
			try {
				statement = connection.createStatement();
				//get results from database
				ResultSet resultSet = statement.executeQuery(SQL_FETCH_CUSTOMERS);
				//get customers from resultset and return them to the app
				return convertResultSetToCustomersArray(resultSet);
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				//close the statement we just used
				if (statement != null){
					try {
						statement.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		}else{
			System.out.println("NO VALID DATABASE CONNECTION, CAN'T FETCH CUSTOMER DATA!");
		}
		// if we reach this point, something went wrong, so return empty list
		return new ArrayList();
	}

	public ArrayList convertResultSetToCustomersArray(ResultSet results) throws SQLException{
		ArrayList customers = new ArrayList();

		//loop the results and add customers to an ArrayList
		while (results.next()){
			customers.add(results.getString("custName"));
		}
		return customers;
	}

        public void initData(){
		CustomerData customerData = new CustomerData();

		ArrayList custArrayList = customerData.fetchCustomerData();

		//get the array from the ArrayList and cast it to a String[]
		customers = (String[]) custArrayList.toArray(new String[0]);
	}
}



    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new billingInfoUI().setVisible(true);
            }
        });
    }

    
    // Variables declaration - do not modify
    private javax.swing.JTextField flatRate;
    private javax.swing.JTextField hoursWorked;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JList workType;
    // End of variables declaration

}
jbodary is offline   Reply With Quote
Old 10-27-2009, 04:40 AM   PM User | #4
sn3twork
New to the CF scene

 
Join Date: Oct 2009
Posts: 9
Thanks: 0
Thanked 0 Times in 0 Posts
sn3twork is an unknown quantity at this point
public ArrayList convertResultSetToCustomersArray
http://java.sun.com/javase/6/docs/ap....html#wasNull()

maybe you could add in some code involving was null to that method to make sure null values from your resultset aren't being entered into your arraylist?
sn3twork is offline   Reply With Quote
Old 10-27-2009, 04:42 AM   PM User | #5
sn3twork
New to the CF scene

 
Join Date: Oct 2009
Posts: 9
Thanks: 0
Thanked 0 Times in 0 Posts
sn3twork is an unknown quantity at this point
ALSO

Code:
public billingInfoUI() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        hoursWorked = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        flatRate = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        workType = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jComboBox1.setModel(new DefaultComboBoxModel(customers));
I'm confused by this your constructor calls initcomponents() which then sets the model for your combobox before customers is ever given any values?
sn3twork is offline   Reply With Quote
Old 10-28-2009, 01:31 AM   PM User | #6
B101T
New to the CF scene

 
Join Date: Oct 2009
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
B101T is an unknown quantity at this point
Quote:
Originally Posted by sn3twork View Post
ALSO

Code:
public billingInfoUI() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        hoursWorked = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        flatRate = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        workType = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jComboBox1.setModel(new DefaultComboBoxModel(customers));
I'm confused by this your constructor calls initcomponents() which then sets the model for your combobox before customers is ever given any values?
I would imagine that that is the problem. I see nothing in the code that instantiates the CustomerData class, let alone changing customers from NULL. Is there a button that you push to fill the "customers" with the information?
B101T is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 03:56 AM.


Advertisement
Log in to turn off these ads.