New to JAVA and working with GUI based application

Trying to build a program for class, and I am absolutely stuck

Page 1 of 1

8 Replies - 1048 Views - Last Post: 02 December 2008 - 02:49 PM Rate Topic: -----

#1 Talonx  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 01-December 08

New to JAVA and working with GUI based application

Posted 01 December 2008 - 11:29 PM

Hello, I have been working on this program for 5 days or so. After coming so far I came to a huge bump "in the road" for lack of a better words. After trying many different things to get this program to work I feel perhaps another set of eyes and minds may help me go in the right direction. Ok to explain what this program is: This program is a GUI based application that has the user connect to a relational database and run SQL queries against it. I have to use MVC style on this program. The program should be flexible enough to take in any database so I come to the problem where I believe I have to use ResultSet and ArrayList to read in an arbitrary amount of columns and rows. This is where my problem lies. I get the data to read in, but instead of multiple rows and columns, my code takes all the data and inputs an entire row of data into one field then moves onto the next field and does the same. So instead of a row of data with user id, name, date. In say 4 fields with 4 columns. I get one row with 5+ columns and all the id, name, date packed into one field. Until there is no more data. Hopefully that made sense. here is my code:

sqlController ( class 1 )
package testProg;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;


public class sqlController {

	private sqlView view;
	private sqlModel model;

	private Connection connection;
	private Statement statement;

	private String[] columnHeadings;

	public sqlController(sqlView view, sqlModel model) {

		this.view = view;
		this.model = model;
		view.getjbtExecuteSQL().addActionListener(new executeSQL());
		view.getjbtConnectDB1().addActionListener(new connectToDB());
		view.getjbtClearSQLCommand().addActionListener(new clearSQLCommand());
		view.getjbtClearSQLResult().addActionListener(new clearSQLResult());

	}

	class executeSQL implements ActionListener {

		public void actionPerformed(ActionEvent e) {

			if (connection == null) {
				view.getjtaSQLResult().setText("Please make a connection to a DB");
				view.getjScrollPane2().setViewportView(view.getjtaSQLResult());
				return;
			}
			else {
				String sqlCommands = view.getjtasqlCommand().getText().trim();
				String[] commands = sqlCommands.replace('\n', ' ').split(";");

				for(String aCommand: commands) {

					if(aCommand.trim().toUpperCase().startsWith("SELECT")) {
						try {
							processSQLSelect(aCommand);
						} catch (SQLException e1) {
							e1.printStackTrace();
						}
					}
					else {
						try {
							processSQLNonselect(aCommand);
						} catch (SQLException e1) {
							e1.printStackTrace();
						}
					}
				}
			}
		}
	}

	public void processSQLSelect(String sqlCommand) throws SQLException {
		statement = connection.createStatement();

		try {
			ResultSet resultSet = statement.executeQuery(sqlCommand);
			int columnCount = resultSet.getMetaData().getColumnCount();

			ArrayList<Object> al = new ArrayList<Object>();
			while (resultSet.next() )
			{
				ArrayList<Object> record = new ArrayList<Object>();

				for (int i = 1; i <= columnCount; i++) 
				{
					Object value = resultSet.getObject(i);
					record.add(value);
				}
				al.add(record);
			}
			columnHeadings = new String[columnCount + 1];
			for(int i = 1; i < columnCount + 1; i++) {
				columnHeadings[i] = new String(resultSet.getMetaData().getColumnName(i));
			}
			view.gettableModel().setColumnIdentifiers(columnHeadings);

			Object[][] tableData = new Object[al.size()][columnCount];

			for(int i = 0; i < al.size(); i++) {
				for(int j = 0; j < columnCount; j++) {
					tableData[i][j] = al.toArray();
				}
			}
			view.gettableModel().addRow(al.toArray());
			view.getjScrollPane2().setViewportView(view.gettableDisplay());
		} 
		catch (java.lang.Exception ex) {
			ex.printStackTrace();
			view.getjScrollPane2().setViewportView(view.getjtaSQLResult());
			view.getjtaSQLResult().setText("Sorry your desired task failed!");
		}
	}

	public void processSQLNonselect(String sqlCommand) throws SQLException {

		statement = connection.createStatement();
		try {
			statement.executeUpdate(sqlCommand);
			view.getjtaSQLResult().setText("Congratulations, it updated! ^_^/>");
		} catch (java.lang.Exception ex) {
			view.getjtaSQLResult().setText("Sorry buddy, your update failed;-;");
		}
		
		view.getjScrollPane2().setViewportView(view.getjtaSQLResult());
	}


	class connectToDB implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			String driver = (String)view.getjcboDriver().getSelectedItem();
			String url = (String)view.getjcboURL().getSelectedItem();
			String username = view.getjtfUsername().getText().trim();
			String password = new String(view.getjpfPassword().getPassword());

			try {
				Class.forName(driver);
				connection = DriverManager.getConnection(url, username, password);
				view.getjlblConnectionStatus().setText("  Connected ^_^/>");
			} catch (java.lang.Exception ex) {
				view.getjlblConnectionStatus().setText("  Error in connecting ~_~;");
			}

			try {
				displayMetaData();
			} catch (java.lang.Exception ex) {
				ex.printStackTrace();
			}

		}

	}

	public void displayMetaData() throws Exception {
		ResultSet rs, rsCol;
		String tableName, colName;

		DefaultMutableTreeNode tableNode, colNode;
		DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Tables"); 

		DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);

		DatabaseMetaData dbMetaData = connection.getMetaData();
		rs = dbMetaData.getTables(null, null, null, new String[] {"TABLE"});

		while (rs.next()){
			tableName=rs.getString("TABLE_NAME");
			tableNode = new DefaultMutableTreeNode(tableName);
			rootNode.add(tableNode);
			rsCol = dbMetaData.getColumns(null,null,tableName,null);
			while (rsCol.next()) {
				colName = rsCol.getString("COLUMN_NAME") + ": "+ 
				rsCol.getString("TYPE_NAME")+ "("+rsCol.getInt("COLUMN_SIZE")+ ")";
				colNode = new DefaultMutableTreeNode(colName);
				tableNode.add(colNode);
			}
			rsCol.close();
		} 
		view.getjtreeMetaData().setModel(treeModel);
		rs.close();
	}

	class clearSQLCommand implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			view.getjtasqlCommand().setText(null);
		}
	}

	class clearSQLResult implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			view.getjtaSQLResult().setText(null);
			view.getjScrollPane2().setViewportView(view.getjtaSQLResult());
		}
	}




}




sqlModel ( class2 ) - does not have any code because no calculations take place

sqlView ( class 3) -

package testProg;


import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.*;

import java.sql.*;
import java.util.Observable;
import java.util.Observer;


public class sqlView extends JFrame {

	// Text area to enter SQL commands
	private JTextArea jtasqlCommand;
	// Text area to display results from SQL commands
	private JTextArea jtaSQLResult;
	private JTextField jtfUsername;
	private JPasswordField jpfPassword;
	private JComboBox jcboURL;
	private JComboBox jcboDriver;
	private JButton jbtExecuteSQL;
	private JButton jbtClearSQLCommand;
	private JButton jbtConnectDB1;
	private JButton jbtClearSQLResult;
	private Border titledBorder1;
	private Border titledBorder2;
	private Border titledBorder3;
	private JLabel jlblConnectionStatus;
	private JTree jtreeMetaData;
	private JScrollPane jScrollPane1;
	private JScrollPane jScrollPane2;
	private JPanel jPanel1;
	private JPanel jPanel2;
	private JPanel jPanel3;
	private JPanel jPanel4;
	private JPanel jPanel5;
	private JPanel jPanel6;
	private JPanel jPanel7;
	private JPanel jPanel8;
	private JPanel jPanel9;
	private JSplitPane splitPane;
	private JTable tableDisplay;
	private DefaultTableModel tableModel;

	//-----------------------------------------------------------------------------------




	public sqlView() {

		jtasqlCommand = new JTextArea();
		jtaSQLResult = new JTextArea();
		
		jtfUsername = new JTextField();
		
		jpfPassword = new JPasswordField();
		
		jcboURL = new JComboBox(new String[] {
				"jdbc:derby://localhost:1527/loanDB",
				"jdbc:odbc:hzExampleDSN","jdbc:odbc:loanDB"});
		jcboDriver = new JComboBox(new String[] {
				"org.apache.derby.jdbc.ClientDriver",
				"sun.jdbc.odbc.JdbcOdbcDriver",
				"com.mysql.jdbc.Driver", 
		"oracle.jdbc.driver.OracleDriver"});
		
		jbtExecuteSQL = new JButton("Execute SQL Command");
		jbtClearSQLCommand = new JButton("Clear");
		jbtConnectDB1 = new JButton("Connect");
		jbtClearSQLResult = new JButton("Clear Result");

		titledBorder1 = new TitledBorder("Enter a SQL Command");
		titledBorder2 = new TitledBorder("SQL Execution Result");
		titledBorder3 = new TitledBorder("Enter Database Information");

		jlblConnectionStatus = new JLabel("Not connected...");

		jtreeMetaData = new JTree();

		jScrollPane1 = new JScrollPane(jtasqlCommand);
		jScrollPane2 = new JScrollPane(jtaSQLResult);

		jPanel1 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		jPanel2 = new JPanel();
		jPanel3 = new JPanel();
		jPanel4 = new JPanel();
		jPanel5 = new JPanel();
		jPanel6 = new JPanel();
		jPanel7 = new JPanel();
		jPanel8 = new JPanel();
		jPanel9 = new JPanel(new FlowLayout(FlowLayout.RIGHT));

		jScrollPane1.setBorder(titledBorder1);
		jScrollPane2.setBorder(titledBorder2);

		jPanel1.add(jbtClearSQLCommand);
		jPanel1.add(jbtExecuteSQL);

		// jPanel2 holds sql command 
		jPanel2.setLayout(new BorderLayout());
		jPanel2.add(jScrollPane1, BorderLayout.CENTER);
		jPanel2.add(jPanel1, BorderLayout.SOUTH);
		jPanel2.setPreferredSize(new Dimension(100, 100));

		// jPanel3 holds connect button and statuss
		jPanel3.setLayout(new BorderLayout());
		jPanel3.add(jlblConnectionStatus, BorderLayout.CENTER);
		jPanel3.add(jbtConnectDB1, BorderLayout.EAST);

		jPanel4.setLayout(new GridLayout(4, 1, 10, 5));
		jPanel4.add(jcboDriver);
		jPanel4.add(jcboURL);
		jPanel4.add(jtfUsername);
		jPanel4.add(jpfPassword);

		jPanel5.setLayout(new GridLayout(4, 1));
		jPanel5.add(new JLabel("JDBC Driver"));
		jPanel5.add(new JLabel("Database URL"));
		jPanel5.add(new JLabel("Username"));
		jPanel5.add(new JLabel("Password"));

		jPanel6.setLayout(new BorderLayout());
		jPanel6.setBorder(titledBorder3);
		jPanel6.add(jPanel4, BorderLayout.CENTER);
		jPanel6.add(jPanel5, BorderLayout.WEST);

		jPanel7.setLayout(new BorderLayout());
		jPanel7.add(jPanel3, BorderLayout.SOUTH);
		jPanel7.add(jPanel6, BorderLayout.CENTER);

		jPanel8.setLayout(new GridLayout(1,2));
		jPanel8.add(jPanel7);
		jPanel8.add(jPanel2);

		jPanel9.add(jbtClearSQLResult);

		jcboURL.setEditable(true);
		jcboDriver.setEditable(true);

		this.add(jPanel8, BorderLayout.NORTH);
		this.add(jPanel9, BorderLayout.SOUTH);

		jtreeMetaData.setModel(null);
		
		tableModel = new DefaultTableModel();
		tableDisplay = new JTable(tableModel);
		
		splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
				new JScrollPane(jtreeMetaData), jScrollPane2);
		splitPane.setOneTouchExpandable(true);
		splitPane.setDividerLocation(250);
		this.add(splitPane, BorderLayout.CENTER);
		this.setSize(650,400);

		
	}


	//-------------------------------------------------------------------------------------------------


	public JScrollPane getjScrollPane1() {
		return jScrollPane1;
	}

	public JScrollPane getjScrollPane2() {
		return jScrollPane2;
	}

	public JPanel getjPanel1() {
		return jPanel1;
	}

	public JPanel getjPanel2() {
		return jPanel2;
	}

	public JPanel getjPanel3() {
		return jPanel3;
	}

	public JPanel getjPanel4() {
		return jPanel4;
	}

	public JPanel getjPanel5() {
		return jPanel5;
	}

	public JPanel getjPanel6() {
		return jPanel6;
	}

	public JPanel getjPanel7() {
		return jPanel7;
	}

	public JPanel getjPanel8() {
		return jPanel8;
	}

	public JPanel getjPanel9() {
		return jPanel9;
	}

	public JSplitPane getsplitPane() {
		return splitPane;
	}

	public JTextField getjtfUsername() {
		return jtfUsername;
	}

	public JPasswordField getjpfPassword() {
		return jpfPassword;
	}

	public JComboBox getjcboURL() {
		return jcboURL;
	}

	public JComboBox getjcboDriver() {
		return jcboDriver;
	}

	public JButton getjbtExecuteSQL() {
		return jbtExecuteSQL;
	}

	public JButton getjbtClearSQLCommand() {
		return jbtClearSQLCommand;
	}

	public JButton getjbtConnectDB1() {
		return jbtConnectDB1;
	}

	public JButton getjbtClearSQLResult() {
		return jbtClearSQLResult;
	}

	public JLabel getjlblConnectionStatus() {
		return jlblConnectionStatus;
	}

	public JTree getjtreeMetaData() {
		return jtreeMetaData;
	}

	public JTextArea getjtasqlCommand() {
		return jtasqlCommand;
	}

	public JTextArea getjtaSQLResult() {
		return jtaSQLResult;
	}

	public Border gettitledBorder1() {
		return titledBorder1;
	}

	public Border gettitledBorder2() {
		return titledBorder2;
	}

	public Border gettitledBorder3() {
		return titledBorder3;
	}
	
	public DefaultTableModel gettableModel() {
		return tableModel;
	}
	
	public JTable gettableDisplay() {
		return tableDisplay;
	}


}



sqlOperate (class 4 ) - this is what I use to run the program

package testProg;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class sqlOperate {
	public static void main(String[] args) {
		
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
			JFrame.setDefaultLookAndFeelDecorated(true);	
			sqlView view = new sqlView();
			sqlModel model = new sqlModel();
			
			new sqlController(view, model);
			view.setVisible(true);
			}
		}); 
	  }
}




I would be very thankful if someone is able to assist me with this. I provided all the code for the program just for reference sake, but I believe my problem lies in the sqlController class which is where I tried to get the metadata to display properly.

Thank you, thank you again to anyone that is able to help me. I eagerly away any responses!

This post has been edited by Talonx: 01 December 2008 - 11:31 PM


Is This A Good Question/Topic? 0
  • +

Replies To: New to JAVA and working with GUI based application

#2 reyben_89  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 69
  • Joined: 30-November 08

Re: New to JAVA and working with GUI based application

Posted 02 December 2008 - 12:18 AM

so your real problem is on sql operate class and you want to solve it right?
Was This Post Helpful? 0
  • +
  • -

#3 reyben_89  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 69
  • Joined: 30-November 08

Re: New to JAVA and working with GUI based application

Posted 02 December 2008 - 12:24 AM

by the way what the filename of your main program? the sqlController or sqlOperate?

and i recompile your code using console and i found 4 errors. 2 errors on sqlController and 2 error sqlOperate. that's is your problem?

This post has been edited by reyben_89: 02 December 2008 - 12:26 AM

Was This Post Helpful? 0
  • +
  • -

#4 Talonx  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 01-December 08

Re: New to JAVA and working with GUI based application

Posted 02 December 2008 - 12:28 AM

View Postreyben_89, on 1 Dec, 2008 - 11:18 PM, said:

so your real problem is on sql operate class and you want to solve it right?


Well its interesting that you put it like that actually. I wasn't 100% sure where the problem could be at. But I figured since the arraylist and resultset are used in the sqlController, that it may have been a problem with that class. Are you saying you found a problem in the sqlOperate? I am very interested to see what exactly your talking about. But to go back to your question and answer it properly, sure...if there is a problem on sqlOperate then I would love to solve it. Hopefully it leads me to understand why the table is messing up.

sqlOperate is the main program that starts the GUI. The program does not give me any errors when I compile it. It could be that you dont have the database needed to run it. Even though it should be compatible enough to run off any database. I have a test one that I use with it.
Was This Post Helpful? 0
  • +
  • -

#5 reyben_89  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 69
  • Joined: 30-November 08

Re: New to JAVA and working with GUI based application

Posted 02 December 2008 - 01:00 AM

View PostTalonx, on 1 Dec, 2008 - 11:28 PM, said:

View Postreyben_89, on 1 Dec, 2008 - 11:18 PM, said:

so your real problem is on sql operate class and you want to solve it right?


sqlOperate is the main program that starts the GUI. The program does not give me any errors when I compile it. It could be that you dont have the database needed to run it. Even though it should be compatible enough to run off any database. I have a test one that I use with it.


am talonx before i forget you said that my problem is in with database. by the way i have mysql server here in my pc. can i use it?
and do you have a messenger so we can converse easily?

and sorry for my last post not this but another one where i state that i found 4 errors.
actually i found 4 errors on sqlOperate and the errors tell me that they cannot find the symbol class sqlModel can you send me the data on sqlModel or i create it without any code inside.

This post has been edited by reyben_89: 02 December 2008 - 01:07 AM

Was This Post Helpful? 0
  • +
  • -

#6 Talonx  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 01-December 08

Re: New to JAVA and working with GUI based application

Posted 02 December 2008 - 01:08 AM

View Postreyben_89, on 2 Dec, 2008 - 12:00 AM, said:

View PostTalonx, on 1 Dec, 2008 - 11:28 PM, said:

View Postreyben_89, on 1 Dec, 2008 - 11:18 PM, said:

so your real problem is on sql operate class and you want to solve it right?


sqlOperate is the main program that starts the GUI. The program does not give me any errors when I compile it. It could be that you dont have the database needed to run it. Even though it should be compatible enough to run off any database. I have a test one that I use with it.


am talonx before i forget you said that my problem is in with database. by the way i have mysql server here in my pc. can i use it?
and do you have a messenger so we can converse easily?


I have AIM, the name is Txmk247
I have the database, enclosed in a file called LoanDB.mdb and LoanDB.idb
I am online right now, for a little while before I pass out, send me a message if you want to converse. And thanks again for any assistance you can give. I should be able to transfer the files to you via AIM if not email when we contact each other
Was This Post Helpful? 0
  • +
  • -

#7 reyben_89  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 69
  • Joined: 30-November 08

Re: New to JAVA and working with GUI based application

Posted 02 December 2008 - 01:15 AM

Quote

I have AIM, the name is Txmk247
I have the database, enclosed in a file called LoanDB.mdb and LoanDB.idb
I am online right now, for a little while before I pass out, send me a message if you want to converse. And thanks again for any assistance you can give. I should be able to transfer the files to you via AIM if not email when we contact each other


i'm have no AIM but i try to download it. i'm using skype and yahoo. and the name is reyben_89. and i be a loyal to you because i'm a begginer in java but i have good analytical skills based on what i experienced in the previous language i learn the visual basic but i'm not also good on it. what in me is i don't know but i'm interested in your problem. thanks for being apreciable.

another problem occured is about on class sqlModel, can you explained it to me?

** Edit ** Fixed quote tags

This post has been edited by no2pencil: 02 December 2008 - 01:20 AM

Was This Post Helpful? 0
  • +
  • -

#8 Talonx  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 01-December 08

Re: New to JAVA and working with GUI based application

Posted 02 December 2008 - 01:26 AM

If anyone else comes up with any ideas about this problem, please feel free to chime in. I will be looking at this forum post again in the morning. Until then folks, cheers~
Was This Post Helpful? 0
  • +
  • -

#9 Talonx  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 01-December 08

Re: New to JAVA and working with GUI based application

Posted 02 December 2008 - 02:49 PM

Problem solved!

Thank you to those that looked this over or attempted in my assistance!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1