Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Return SQL Query to JList in Java

Posted on 2009-03-29
6
Medium Priority
?
6,041 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 1600 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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
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 400 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

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn different types of Android Layout and some basics of an Android App.
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
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 video teaches viewers about errors in exception handling.
Suggested Courses

610 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