Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 6163
  • Last Modified:

Return SQL Query to JList in Java

I need some assistance returning the query I wrote into a JList.  A worthy example might be enough for me to get the task done.

The code below compiles and connects to the database, so the only task left to do is populate the JList with the data.
/****************************************************************/
/*                      ReportPatientBilling	                            */
/*                                                              */
/****************************************************************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.sql.*;
import java.lang.*;
 
/**
 * Summary description for ReportPatientBilling
 *
 */
public class ReportPatientBilling2 extends JFrame
{
	// Variables declaration
	private JLabel jLabel1;
	private JLabel jLabel2;
	private JTextField txtRunReport;
	private JList jList1;
	private JScrollPane jScrollPane2;
	private JButton jButton1;
	private JPanel contentPane;
	// End of variables declaration
 
 
	public ReportPatientBilling2()
	{
		super();
		initializeComponent();
		//
		// TODO: Add any constructor code after initializeComponent call
		//
 
		this.setVisible(true);
	}
 
	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always regenerated
	 * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
	 * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
	 * to retrieve your design properly in future, before revising this method.
	 */
	private void initializeComponent()
	{
		jLabel1 = new JLabel();
		jLabel2 = new JLabel();
		txtRunReport = new JTextField();
		jList1 = new JList();
		jScrollPane2 = new JScrollPane();
		jButton1 = new JButton();
		contentPane = (JPanel)this.getContentPane();
 
		//
		// jLabel1
		//
		jLabel1.setText("Due Date:");
		//
		// jLabel2
		//
		jLabel2.setText("Report on Patient Billing");
		//
		// txtRunReport
		//
		txtRunReport.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				txtRunReport_actionPerformed(e);
			}
 
		});
		//
		// jList1
		//
		jList1.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e)
			{
				jList1_valueChanged(e);
			}
 
		});
		//
		// jScrollPane2
		//
		jScrollPane2.setViewportView(jList1);
		//
		// jButton1
		//
		jButton1.setText("Run Report");
		jButton1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				jButton1_actionPerformed(e);
			}
 
		});
		//
		// contentPane
		//
		contentPane.setLayout(null);
		addComponent(contentPane, jLabel1, 34,119,111,22);
		addComponent(contentPane, jLabel2, 163,13,137,18);
		addComponent(contentPane, txtRunReport, 111,121,151,22);
		addComponent(contentPane, jScrollPane2, 23,174,412,214);
		addComponent(contentPane, jButton1, 154,53,153,28);
		//
		// ReportPatientBilling
		//
		this.setTitle("ReportPatientBilling - extends JFrame");
		this.setLocation(new Point(0, 0));
		this.setSize(new Dimension(466, 431));
	}
 
	/** Add Component Without a Layout Manager (Absolute Positioning) */
	private void addComponent(Container container,Component c,int x,int y,int width,int height)
	{
		c.setBounds(x,y,width,height);
		container.add(c);
	}
 
	//
	// TODO: Add any appropriate code in the following Event Handling Methods
	//
	private void txtRunReport_actionPerformed(ActionEvent e)
	{
		System.out.println("\ntxtRunReport_actionPerformed(ActionEvent e) called.");
		// TODO: Add any handling code here
 
	}
 
	private void jList1_valueChanged(ListSelectionEvent e)
	{
		System.out.println("\njList1_valueChanged(ListSelectionEvent e) called.");
		if(!e.getValueIsAdjusting())
		{
			Object o = jList1.getSelectedValue();
			System.out.println(">>" + ((o==null)? "null" : o.toString()) + " is selected.");
			// TODO: Add any handling code here for the particular object being selected
			
		}
	}
 
//*******THIS IS WHERE THE QUERY IS RUN AND THE LIST BOX IS POPULATED**********
	private void jButton1_actionPerformed(ActionEvent e)
	{
		System.out.println("\njButton1_actionPerformed(ActionEvent e) called.");
		// TODO: Add any handling code here
		String varDueDate;
		varDueDate = txtRunReport.getText();	
	
		String url = "jdbc:mysql://localhost:3306/";
   	String dbName = "onehourclinic";
 	   String driver = "com.mysql.jdbc.Driver";
 	   String userName = "root";
 	   String password = "******";
 	   int code;
   	String description;
					 
		try{
		Class.forName(driver).newInstance();
  		Connection conn = DriverManager.getConnection(url+dbName,userName,password);
      System.out.println("Connected to the database");
 
        //Create a Statement
      Statement stmt = conn.createStatement ();
		System.out.println("Connected to the database2");
		
		 ResultSet rset = stmt.executeQuery(" SELECT TOT_DUE, DUE_DATE, CONDITIONS.DESCRIPTION, " 
	   + " PATIENT.LNAME, PATIENT.STATE, PATIENT.ZIP FROM CONDITIONS, PATIENT, PAT_BILL WHERE " +
	   " PCODE=CODE AND PATIENT.PID_NUM=PAT_BILL.PATIENT_NUM AND DUE_DATE > '"+varDueDate+"'  " +
		" AND TOT_DUE > 0 ");
 
		//*****PUt the select rows into the jlist here***********
		//*****
		//*****
		//******************************************************
 
	 	System.out.println("Connected to the database3");
		
		
	 } catch (Exception e2) {
      System.out.println("EXECPTION E2");
	   e2.printStackTrace();
    }
	
 
		
 
	}
 
	//
	// TODO: Add any method code to meet your needs in the following area
	//
 
 
 
 
//============================= Testing ================================//
//=                                                                    =//
//= The following main method is just for testing this class you built.=//
//= After testing,you may simply delete it.                            =//
//======================================================================//
	public static void main(String[] args)
	{
		JFrame.setDefaultLookAndFeelDecorated(true);
		JDialog.setDefaultLookAndFeelDecorated(true);
		try
		{
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		}
		catch (Exception ex)
		{
			System.out.println("Failed loading L&F: ");
			System.out.println(ex);
		}
		new ReportPatientBilling2();
	}
//= End of Testing =
 
 
}

Open in new window

0
johngabrielson2008
Asked:
johngabrielson2008
  • 2
  • 2
  • 2
3 Solutions
 
basav_comCommented:
Check this:

//*always start class names with a Capital Letter: RetrievalGUI
class RetrivalGUI extends JFrame{

//*name the methods according to what they do
public void buildTheFrame(){

//Create a new DefaultListModel
DefaultListModel dlm = new DefaultListModel();

//for speed we find out what size to make our list model first
ResultSet rs = con.createStatement("SELECT COUNT(*) as NumRows FROM tblSongs");
int listLength = rs.getInteger("NumRows");
dlm.ensureCapacity(listLength);

//Run the SQL query, reuse the rs resultset
ResultSet rs = con.createStatement("SELECT * FROM tblSongs");

String toAdd;
//while the resultset has a next(){
while(rs.next()){

//get all the bits of data out of the resultset row
toAdd = rs.getString("Artist") + " - " + rs.getString(Title);

//add() them to the DefaultListModel
dlm.add(toAdd);
}

//make a new JList based on our now-populated DefaultListModel
JList jl = new JList(dlm);

//set the layout of the frame
this.setLayout(new FLowLayout)

//add the jlist to the frame
this.getContentpane().add(jl);

//show the frame..
this.pack();
this.show();


For more info: http://www.codeguru.com/forum/archive/index.php/t-311273.html
0
 
InteractiveMindCommented:
If you want all of the columns to appear, you'd use a JTable rather than a JList..
0
 
johngabrielson2008Author Commented:
basav_com: -- I have been eyeing that code, but it has some flaws in it.  When I try to use it, here is the error I receive trying to get the count.

ReportPatientBilling2.java:177: cannot find symbol
symbol  : method getInteger(java.lang.String)
location: interface java.sql.ResultSet
            int listLength = rs.getInteger("NumRows");

InteractiveMind:
Can you provide an example of how to load it?  Using either one, I am at a loss on how to load it.
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
InteractiveMindCommented:
Read the data from the ResultSet, as illustrated here:
http://www.exampledepot.com/egs/java.sql/GetRsData.html?l=rel

Then just add the read values to the JList or JTable. In the latter case, here's a tutorial:
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
0
 
basav_comCommented:
symbol  : method getInteger(java.lang.String)
location: interface java.sql.ResultSet
            int listLength = rs.getInteger("NumRows");  


-------------> You have to use the column names from your table not the one 'NumRows'.
0
 
johngabrielson2008Author Commented:
basav_com:

I created a new sql statement with a Count(*) as NumRows and it still failed.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now