13 Replies - 7919 Views - Last Post: 26 October 2009 - 07:04 PM Rate Topic: -----

#1 jbodary  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 24-October 09

How do I populate a jcombobox with information from a mySQL database?

Post icon  Posted 24 October 2009 - 04:11 PM

Title says it all.. Basically the program takes customer information and dumps it in a database. In order to change information I want the user to be able to pick a customer name from a combobox, so the system can then call all the info out of the database on that customer. Accessing the database is fine, putting info in and changing it is fine.. I just cant figure out how to get the combobox to populate with all the customer names.
Is This A Good Question/Topic? 0
  • +

Replies To: How do I populate a jcombobox with information from a mySQL database?

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10649
  • View blog
  • Posts: 39,548
  • Joined: 27-December 08

Re: How do I populate a jcombobox with information from a mySQL database?

Posted 24 October 2009 - 04:15 PM

Check out the JComboBox and ResultSet classes.

http://java.sun.com/.../ResultSet.html
http://java.sun.com/.../JComboBox.html

You may also want to consider using an Array. Feel free to post if you have any more problems. Remember to include your code. :)
Was This Post Helpful? 0
  • +
  • -

#3 jbodary  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 24-October 09

Re: How do I populate a jcombobox with information from a mySQL database?

Posted 24 October 2009 - 04:30 PM

Thanks, sadly I am still confused.
This is what I have so far, but it keeps throwing a class not found exception.

	private void queryCustomer(){
			jComboBox1.addItem("(Choose Customer)");			
try {
			
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://jbodary27.db.4902100.hostedresource.com/jbodary27";
			Connection conn = DriverManager.getConnection(url,"jbodary27","Alantis1");
			Statement st = conn.createStatement();
			ResultSet rs = st.executeQuery("SELECT custName FROM customers");
			while	(rs.next()){
				 jComboBox1.addItem(rs.getString(1)+"-"+rs.getString(2));
			}
			rs.close();
			st.close();
} catch (SQLException e) {
			e.printStackTrace();
		}
	}


Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10649
  • View blog
  • Posts: 39,548
  • Joined: 27-December 08

Re: How do I populate a jcombobox with information from a mySQL database?

Posted 24 October 2009 - 04:33 PM

Query the database for customers and store the result into a ResultSet object. From there, go through and retrieve each customer as a String and add it to an ArrayList. From there, convert the ArrayList to an array and use that as a parameter in the JComboBox's constructor. Just remember, when you go to get the value, you will have to explicitly cast the result into a String because the JComboBox's getter method returns an Object value.
Was This Post Helpful? 0
  • +
  • -

#5 jbodary  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 24-October 09

Re: How do I populate a jcombobox with information from a mySQL database?

Posted 24 October 2009 - 05:52 PM

Have any code examples that would help? Am feeling very out of my depth but this is the only things thats left for me to finish dratit.
Was This Post Helpful? 0
  • +
  • -

#6 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10649
  • View blog
  • Posts: 39,548
  • Joined: 27-December 08

Re: How do I populate a jcombobox with information from a mySQL database?

Posted 24 October 2009 - 06:45 PM

What Object specifically are you having trouble with? Is it the ResultSet, ArrayList, array or JComboBox? Please be specific as to the area you are uncomfortable with and what you are unsure about. I'll provide one example on the topic of your choice, and let you go from there. :)
Was This Post Helpful? 0
  • +
  • -

#7 jbodary  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 24-October 09

Re: How do I populate a jcombobox with information from a mySQL database?

Posted 24 October 2009 - 06:59 PM

arrays, they have always confused the crap outta me
Was This Post Helpful? 0
  • +
  • -

#8 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10649
  • View blog
  • Posts: 39,548
  • Joined: 27-December 08

Re: How do I populate a jcombobox with information from a mySQL database?

Posted 24 October 2009 - 07:06 PM

View Postjbodary, on 24 Oct, 2009 - 07:59 PM, said:

arrays, they have always confused the crap outta me


Really, the arrays one is quite easy for this topic. Given the filled ArrayList<String> object (we'll call it custList), we convert it to an array of Strings like so:

String[] customers = custList.toArray(new String[custList.size()];



From there, feed this as the parameter into the JComboBox constructor. If you need any more help, feel free to post your questions along with your code. Good luck! :)

*For more about arrays, take a look at the following links:
http://java.sun.com/...lts/arrays.html
http://leepoint.net/...ays/arrays.html
Was This Post Helpful? 0
  • +
  • -

#9 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8342
  • View blog
  • Posts: 31,880
  • Joined: 06-March 08

Re: How do I populate a jcombobox with information from a mySQL database?

Posted 24 October 2009 - 07:47 PM

	private void queryCustomer(){
			jComboBox1.addItem("(Choose Customer)");			



JComboBox is supposed to offer you data from your database/array/,,,,
surely not to hold a title
you are on the wrong way
Was This Post Helpful? 0
  • +
  • -

#10 jbodary  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 24-October 09

Re: How do I populate a jcombobox with information from a mySQL database?

Posted 26 October 2009 - 05:09 PM

Ok.. here goes nothing. I think I am close, but it is still not working - I know I am missing something simple here.

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

public class billingInfoUI extends javax.swing.JFrame {

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

		jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Billing Information", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.ABOVE_BOTTOM, new java.awt.Font("Bleeding Cowboys", 0, 48))); // NOI18N

		javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout.setHorizontalGroup(
			jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGap(0, 457, Short.MAX_VALUE)
		);
		jPanel1Layout.setVerticalGroup(
			jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGap(0, 0, Short.MAX_VALUE)
		);

		hoursWorked.setHorizontalAlignment(javax.swing.JTextField.CENTER);
		hoursWorked.setText("Hours Worked");
		hoursWorked.setBorder(null);

		jLabel1.setText("Or");

		flatRate.setHorizontalAlignment(javax.swing.JTextField.CENTER);
		flatRate.setText("Flat Rate");
		flatRate.setBorder(null);

		workType.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Work Type", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP));
		workType.setModel(new javax.swing.AbstractListModel() {
			String[] strings = { "Web Design", "Graphic Design", "Consulting" };
			public int getSize() { return strings.length; }
			public Object getElementAt(int i) { return strings[i]; }
		});
		workType.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
		jScrollPane1.setViewportView(workType);

		jList2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Any Extras?", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP));
		jList2.setModel(new javax.swing.AbstractListModel() {
			String[] strings = { "Blog", "Forum", "Templating", "Rush Delivery" };
			public int getSize() { return strings.length; }
			public Object getElementAt(int i) { return strings[i]; }
		});
		jScrollPane2.setViewportView(jList2);

		jButton1.setText("Save");
		jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				jButton1MouseClicked(evt);
			}
		});

		jButton2.setText("Invoice");

		jButton3.setText("Close");
		jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				jButton3MouseClicked(evt);
			}
		});
		jButton3.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton3ActionPerformed(evt);
			}
		});

		jComboBox1.setModel(customers);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(
			layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGroup(layout.createSequentialGroup()
				.addContainerGap()
				.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
			.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
				.addContainerGap(89, Short.MAX_VALUE)
				.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
					.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
						.addComponent(hoursWorked, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addGap(48, 48, 48)
						.addComponent(jLabel1)
						.addGap(1, 1, 1))
					.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
						.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addGap(31, 31, 31)))
				.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
					.addGroup(layout.createSequentialGroup()
						.addGap(18, 18, 18)
						.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
					.addGroup(layout.createSequentialGroup()
						.addGap(49, 49, 49)
						.addComponent(flatRate, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)))
				.addGap(79, 79, 79))
			.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
				.addGap(62, 62, 62)
				.addComponent(jButton1)
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 103, Short.MAX_VALUE)
				.addComponent(jButton2)
				.addGap(79, 79, 79)
				.addComponent(jButton3)
				.addGap(52, 52, 52))
			.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
				.addContainerGap(134, Short.MAX_VALUE)
				.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
				.addGap(107, 107, 107))
		);
		layout.setVerticalGroup(
			layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGroup(layout.createSequentialGroup()
				.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
				.addGap(30, 30, 30)
				.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
					.addComponent(hoursWorked, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
					.addComponent(flatRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
					.addComponent(jLabel1))
				.addGap(20, 20, 20)
				.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
					.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
					.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
				.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
				.addGap(51, 51, 51)
				.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
					.addComponent(jButton2)
					.addComponent(jButton3)
					.addComponent(jButton1))
				.addContainerGap())
		);

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


	private static final String JDBC_CONNECTION_URL	= "jdbc:mysql://localhost/test";

	private static final String DATABASE_USER 		= "root";

	private static final String DATABASE_PASSWORD	= "root";

	private static final String SQL_FETCH_CUSTOMERS = "SELECT custName FROM customers";

	private Connection connection = null;


	public CustomerData(){
		initConnection();
	}


	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();
				ResultSet resultSet = statement.executeQuery(SQL_FETCH_CUSTOMERS);
				return convertResultSetToCustomersArray(resultSet);
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {

				if (statement != null){
					try {
						statement.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		}else{
			System.out.println("NO VALID DATABASE CONNECTION, CAN'T FETCH CUSTOMER DATA!");
		}
		return new ArrayList();
	}

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

		while (results.next()){
			customers.add(results.getString("custName"));
		}
		return customers;
	}
}

	private void initData(){
		CustomerData customerData = new CustomerData();
		
		ArrayList custArrayList = customerData.fetchCustomerData();
		
		customers = (String[]) custArrayList.toArray(new String[0]);
	}

	/**
	* @param args the command line arguments
	*/
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new billingInfoUI().setVisible(true);
			}
		});
	}
	private String[] customers = null;
	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;


}



Was This Post Helpful? 0
  • +
  • -

#11 jbodary  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 24-October 09

Re: How do I populate a jcombobox with information from a mySQL database?

Posted 26 October 2009 - 06:40 PM

code with the excess taken out...

jComboBox1.setModel(customers);


public class CustomerData {

private static final String JDBC_CONNECTION_URL = "jdbc:mysql://localhost/test";
private static final String DATABASE_USER			   = "root";
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(){
		initConnection();
}


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!");
		}
		return new ArrayList();
}

private 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;
}
	private String[] customers = null;
	private 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]);
}


Was This Post Helpful? 0
  • +
  • -

#12 jbodary  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 24-October 09

Re: How do I populate a jcombobox with information from a mySQL database?

Posted 26 October 2009 - 06:57 PM

Ok, fixed part of the problem I think - but now it says that it cant find the variable customers...


jComboBox1.setModel(new DefaultComboBoxModel(customers));




public class CustomerData {

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


Was This Post Helpful? 0
  • +
  • -

#13 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8342
  • View blog
  • Posts: 31,880
  • Joined: 06-March 08

Re: How do I populate a jcombobox with information from a mySQL database?

Posted 26 October 2009 - 07:01 PM

GUI generated by an IDE
Sorry... I won't even try to reply to it
Write your own GUI we can help
I am not to go through the process of identifying WHERE in your GUI generator you clciked the wrong option
This forum help people with Java code THEY produced, not the one a GUI generastor produced
Was This Post Helpful? 0
  • +
  • -

#14 jbodary  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 24-October 09

Re: How do I populate a jcombobox with information from a mySQL database?

Posted 26 October 2009 - 07:04 PM

Um, of the code posted in my last reply, about 3 words of it was generated.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1