Solved

Return SQL Query to JList in Java

Posted on 2009-03-29
6
5,790 Views
Last Modified: 2013-11-23
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
Comment
Question by:johngabrielson2008
  • 2
  • 2
  • 2
6 Comments
 
LVL 12

Expert Comment

by:basav_com
ID: 24013617
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
 
LVL 25

Assisted Solution

by:InteractiveMind
InteractiveMind earned 400 total points
ID: 24013715
If you want all of the columns to appear, you'd use a JTable rather than a JList..
0
 
LVL 1

Accepted Solution

by:
johngabrielson2008 earned 0 total points
ID: 24013786
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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 25

Expert Comment

by:InteractiveMind
ID: 24013901
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
 
LVL 12

Assisted Solution

by:basav_com
basav_com earned 100 total points
ID: 24017327
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
 
LVL 1

Author Comment

by:johngabrielson2008
ID: 24030917
basav_com:

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

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
bunnyEars2 challenge 6 67
changePi Challenge 15 75
How Complex Is This Java Course ? 9 63
countAbc challenge 9 49
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now