7 Replies - 4594 Views - Last Post: 30 November 2011 - 02:51 PM Rate Topic: ***-- 2 Votes

#1 mnosek3  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 32
  • Joined: 10-September 11

Database JDBC-Displaying a table as a gui?

Posted 28 November 2011 - 06:08 PM

Hi! I am trying to create an application that will allow a user to enter one SQL query command and the application will display the results in a gui JTable.

This will only be used for displaying.

I have come up with the following code. My program consists of the following classes: CreateConnection, GuiScreen, QueryTableModel and TestDriver.


When I try to run my application I get a null pointerException.Could some one please help me fix the problem with my application?

Any help is greatly apprenticed! I am trying to learn java and this is one of my first projects.


Any suggestions on how to better display the results of a query in a JTable?

Many Thanks! :)







package lab5.ids401.uic.edu;

import edu.uic.ids401.util.*;
import java.sql.*;
import java.util.*;
import java.sql.*;


public class CreateConnection {

static Connection getConnection(){
	
	String driver ="com.mysql.jdbc.Driver";
	String url = "jdbc:mysql://131.193.211.171:3306/ids517";
	String userName = "scott";
	String password ="tiger";
	
	
	Connection con = null;
	
	try
	{
		Class.forName(driver).newInstance();
	}
	catch (Exception ex)
	{
		System.out.println("Check classpath. Cannot load database driver"+driver);
	}
	
	try
	{
		con = DriverManager.getConnection(url,userName,password);
	}
	catch (SQLException e)
	{
		System.out.println("Driver loaded, but cannot connect to database"+url);
	}
	
return con;

}	
	
}





package lab5.ids401.uic.edu;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;

import javax.swing.*;
import javax.swing.table.*;

public class GuiScreen extends JFrame {
	
	private static final long serialVersionUID = 1L;
	
	public static final int WIDTH = 1280;
	public static final int HEIGHT = 1024;
	
	private JTextField sqlQuery;
	
	QueryTableModel qtm;
	
	public void display()
	{

	setSize(WIDTH,HEIGHT);
	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	
	setLayout(new BorderLayout());
	
	JPanel inputPanel = new JPanel();
	inputPanel.setLayout(new GridLayout(0,2));
	
	inputPanel.add(new JLabel(""));
	inputPanel.add(new JLabel(""));
	
	inputPanel.add(new JLabel("SQL Query:"));
	sqlQuery = new JTextField("");
	sqlQuery.setBackground(Color.WHITE);
	inputPanel.add(sqlQuery);
	
	inputPanel.add(new JLabel(""));
	inputPanel.add(new JLabel(""));
	
	
	JButton Execute = new JButton("Execute");
	inputPanel.add(Execute);
	
	Execute.addActionListener(new ActionListener(){
		public void actionPerformed(ActionEvent e){
			try {
				qtm.setQuery(sqlQuery.getText().trim());
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	});
	
	
	JButton Exit = new JButton("Exit");
	inputPanel.add(Exit);
	

	qtm = new QueryTableModel();
	JTable table = new JTable(qtm);
	JScrollPane scrollpane = new JScrollPane(table);
	JPanel tablePanel = new JPanel();
	tablePanel.add(scrollpane);
	
	
	add(inputPanel,BorderLayout.NORTH);
	add(tablePanel,BorderLayout.SOUTH);
	
	
	
	
	}
	
	
}




package lab5.ids401.uic.edu;

import java.awt.*;
import edu.uic.ids401.util.*;
import java.sql.*;
import java.util.*;
import java.sql.*;

import java.util.Vector;

import javax.swing.table.AbstractTableModel;

public class QueryTableModel extends AbstractTableModel {

	private static final long serialVersionUID = 1L;
	
	Vector<String[]> cache;
	int colCount;
	String[] headers;
	
	Connection conn; 
	Statement st;
	
	public String getColumnName(int i)
	{
		return headers[i];
	}
	
	public int getColumnCount()
	{
		return colCount;
	}
	
	public int getRowCount()
	{
		return cache.size();
	}
	
	public Object getValueAt(int row, int col)
	{
		return ((String[]) cache.elementAt(row))[col];
	}
	
	
	public void setQuery(String sqlQuery) throws SQLException
	{
		cache = new Vector<String[]>();
		
		Connection conn =CreateConnection.getConnection();
		System.out.println("Got Connection");
		
		Statement st = conn.createStatement();
		
		st = conn.createStatement();
		
		try
		{
			ResultSet rs = st.executeQuery(sqlQuery);
			ResultSetMetaData meta = rs.getMetaData();
			colCount = meta.getColumnCount();
			///Execute the query and store the result set and its metadata
			
			headers = new String[colCount];
				for(int i=1;i<colCount;i++)
				{
					headers[i-1]=meta.getColumnName(i);
				}
			///Rebuild the headers array with the new column names
				
			while(rs.next())
			{
				String[] record = new String[colCount];
					for(int i=0;i<colCount;i++)
					{
						record[i]=rs.getString(i+1);
					}
				cache.addElement(record);
			}
			
			fireTableChanged(null);
			
		}
		catch(Exception e)
		{
			cache = new Vector<String[]>();
			e.printStackTrace();
		}
		
		
	}
	
}





package lab5.ids401.uic.edu;

import java.sql.SQLException;

public class TestDriver {


	public static void main(String[] args) throws SQLException {
	
		GuiScreen screen = new GuiScreen();
		
		screen.display();
		
		screen.setVisible(true);
		
	

	}

}


This post has been edited by mnosek3: 28 November 2011 - 06:12 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Database JDBC-Displaying a table as a gui?

#2 pbl  Icon User is offline

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

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Database JDBC-Displaying a table as a gui?

Posted 28 November 2011 - 06:43 PM

View Postmnosek3, on 28 November 2011 - 09:08 PM, said:

When I try to run my application I get a null pointerException.

Where ?
Was This Post Helpful? 1
  • +
  • -

#3 mnosek3  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 32
  • Joined: 10-September 11

Re: Database JDBC-Displaying a table as a gui?

Posted 29 November 2011 - 08:14 AM

View Postpbl, on 28 November 2011 - 06:43 PM, said:

View Postmnosek3, on 28 November 2011 - 09:08 PM, said:

When I try to run my application I get a null pointerException.

Where ?



cache = new Vector<String[]>();




I think its right here. What is a null pointer?
Was This Post Helpful? 0
  • +
  • -

#4 mnosek3  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 32
  • Joined: 10-September 11

Re: Database JDBC-Displaying a table as a gui?

Posted 29 November 2011 - 02:07 PM

The null pointer exception is in the getRowCount() method. It returns cache.size();

Could someone please help me figure this out? My project is due tomorrow!

Thanks!
Was This Post Helpful? 0
  • +
  • -

#5 pbl  Icon User is offline

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

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Database JDBC-Displaying a table as a gui?

Posted 29 November 2011 - 02:39 PM

That will happen because the JTable GUI trys to draw the JTable before you have actually field the VEctor with your SQL statement
A quick and dirty patch would be
   public int getRowCount()  
     { 
        if(cache == null)
           return 0; 
        return cache.size();  
     }  


The way it should be done is that you should create the cache Vactor in your constructor of your Model, even if it is empty at that moment. Then when you execute a SQL statement instead of

        cache = new Vector<String[]>();  
        Connection conn =CreateConnection.getConnection();  


do
        cache.clear();  
        Connection conn =CreateConnection.getConnection();  


Happy coding
Was This Post Helpful? 1
  • +
  • -

#6 mnosek3  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 32
  • Joined: 10-September 11

Re: Database JDBC-Displaying a table as a gui?

Posted 29 November 2011 - 03:33 PM

pbl, thank you so much! You're the man!
Was This Post Helpful? 0
  • +
  • -

#7 mnosek3  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 32
  • Joined: 10-September 11

Re: Database JDBC-Displaying a table as a gui?

Posted 30 November 2011 - 02:15 PM

My application works fine and I am able to run all the querys I need. But the JTable is sometimes showing up to small. Is there a way I could re-size the Table to fit my window. I tired the following code but it doesn't seem to do anything. Once again thanks for all your help!



qtm = new QueryTableModel();
	JTable table = new JTable(qtm);
	table.setSize(new Dimension(900,952));
	
	JScrollPane scrollpane = new JScrollPane(table);
	scrollpane.setSize(new Dimension(900,952));
	
	JPanel tablePanel = new JPanel();
	tablePanel.setSize(new Dimension(900,952));
	tablePanel.add(scrollpane);
	
	
	add(inputPanel,BorderLayout.NORTH);
	add(tablePanel,BorderLayout.CENTER);





I tried to change the dimensions of the Jtable, scrollpane and the panel but no matter what I do I get the same results... How do I re size this?

This post has been edited by mnosek3: 30 November 2011 - 02:15 PM

Was This Post Helpful? 0
  • +
  • -

#8 pbl  Icon User is offline

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

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Database JDBC-Displaying a table as a gui?

Posted 30 November 2011 - 02:51 PM

By default JScrollPane uses ScrollPaneLayout to handle the layout of its child Components. ScrollPaneLayout determines the size to make the viewport view in one of two ways:

1) If the view implements Scrollable a combination of getPreferredScrollableViewportSize, getScrollableTracksViewportWidth and getScrollableTracksViewportHeightis used,
2) otherwise getPreferredSize is used.

So it is simply a setPreferredSize() on the JScrollPane that you should do
remove all your other setSize() :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1