Hey guys, Well I had a few questions, so I have an employee Database with id,fname,lname,dep and I wasn't sure if I should do and Employee class whit constructor and what not, and make the class read the information form the Database and then create and ArrayList<employee> and fill it up and have my Table java read from my class with the arraylist or should I just fill up the table directly from the returned queries.
I really dont know to do the last part, but i have done various little projects with Arraylist<Type> and things like that. Do you'll have any suggestions?

Recommended Answers

All 5 Replies

Well, what I do is:

A class called Employee that represents a single instance of an employee. Probably corresponding to a row from your Employee table. Possible containing related or derived employee data as well. How you expose the properties of your Employee class is a design decision only you can make...

With classes that reflect a table row I often make a constructor that takes a ResultSet row as an argument. Whether that's exposed to the public or encapsulated is another design decision you have to make with a view to your application's architecture.

If you want something that would conceptually correspond to an ArrayList<Employee> then I would call that EmployeeList or EmployeeTable (if it was your explicit intention to use it to reflect the entire employee table... which would be a bad design decision because of scalability issues). You could declare class EmployeeTable extends ArrayList<Employee> and give it a constructor that tables a query (string or object), which it would use to obtain and instantiate the list members.

You're not getting many answers because we have no idea how you intend to use your employee data so we can't offer specific advice - just statements of principle, which aren't usually that helpful...

Well, what I do is:

A class called Employee that represents a single instance of an employee. Probably corresponding to a row from your Employee table. Possible containing related or derived employee data as well. How you expose the properties of your Employee class is a design decision only you can make...

With classes that reflect a table row I often make a constructor that takes a ResultSet row as an argument. Whether that's exposed to the public or encapsulated is another design decision you have to make with a view to your application's architecture.

If you want something that would conceptually correspond to an ArrayList<Employee> then I would call that EmployeeList or EmployeeTable (if it was your explicit intention to use it to reflect the entire employee table... which would be a bad design decision because of scalability issues). You could declare class EmployeeTable extends ArrayList<Employee> and give it a constructor that tables a query (string or object), which it would use to obtain and instantiate the list members.

You're not getting many answers because we have no idea how you intend to use your employee data so we can't offer specific advice - just statements of principle, which aren't usually that helpful...

Since it's my first time using swing in java, what i really want is to be able to display a JTable with the rows and columns of the result from the query...

Select id,fname,lname,dep From Employee;

And display that something like:

ID FName LName Dep
1 Jose Garcia Electronics
2 John Green Electronics
3 Fernando Garcia Home Improvement
4 Jose Hernandez Electronics


etc.. I've done this but I read the information from a .txt used some kind of tokenizer and saved inside an ArrayList<Employee> and modified with some methods and things like that and at the end of the program all it did was create a new .txt with the information or rewrite on it, but i'm not sure how to do it with the results from the query...

Okay, you're good with supplying a JTable with data, so I'll stick with the db side of things. I presume you're able to get a db connection going. This is very platform-specific and I'd need detailed information to help with that side. Here is the code I would use (using a method to show where the connection is coming from):

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

List<Employee> loadEmployees (Connection dbConn) throws SQLException {
  List<Employee> empList = new ArrayList<Employee> ();
  Statement stmt = dbConn.createStatement (ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  ResultSet rs = stmt.executeQuery ("Select id,fname,lname,dep From Employee");
  while (rs.next ()) {
    empList.add (new Employee (rs)); // for the sake of argument...
  }
  rs.close ();
  stmt.close ();
  return empList;
}

This code will return with an arraylist similar to what you would end up with if you'd read it from a text file.

Hope that helps...

Okay, you're good with supplying a JTable with data, so I'll stick with the db side of things. I presume you're able to get a db connection going. This is very platform-specific and I'd need detailed information to help with that side. Here is the code I would use (using a method to show where the connection is coming from):

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

List<Employee> loadEmployees (Connection dbConn) throws SQLException {
  List<Employee> empList = new ArrayList<Employee> ();
  Statement stmt = dbConn.createStatement (ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  ResultSet rs = stmt.executeQuery ("Select id,fname,lname,dep From Employee");
  while (rs.next ()) {
    empList.add (new Employee (rs)); // for the sake of argument...
  }
  rs.close ();
  stmt.close ();
  return empList;
}

This code will return with an arraylist similar to what you would end up with if you'd read it from a text file.

Hope that helps...

(Sorry that I don't use very professional words to describe my problem, I'm not that good at representing my data in a professional way)

Yeah, it does help, I just wasn't sure what would be the best way to represent the result from the query,I mean the most professional way.

So i could do something like this?

while (rs.next ()) {
    int id = rs.getInt("id");
    String usr_name = rs.getString("usr_name");
    String pass = rs.getString("pass");
    Employee emp = new Employee(id,usr_name,pass); //Saying we had a constructor Employee
  }

And then do something like:

CatalogEmployee.addEmployee(emp);//Class CatalogEmployee with Arraylist<Employee>

Similar to this C# code i have:

class CatalogoProductos
    {
        private List<producto> catalogoProductos;

        public CatalogoProductos()
        {
            catalogoProductos = new List<producto>();
        }
        public void addProducto(producto prod)
        {
            catalogoProductos.Add(prod);
        }
        public void removeProducto(producto prod)
        {
            catalogoProductos.Remove(prod);
        }
        public int getNumberProductos()
        {
            return catalogoProductos.Count;
        }
        public producto getProducto(int index)
        {
            return catalogoProductos.ElementAt<producto>(index);
        }
        public producto getProducto(string clv)
        {
            foreach (producto prod in catalogoProductos)
            {
                if (prod.getClave().Equals(clv))
                {
                    return prod;
                }
            }
            return null;
        }
    }

I really hope you understand me, because i think it sounds confusing
Also another problem I had is that for a JTable you use something like this:

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class JTableCreatingDemo {
  public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Object rowData[][] = { { "Row1-Column1", "Row1-Column2", "Row1-Column3" },
        { "Row2-Column1", "Row2-Column2", "Row2-Column3" } };
    Object columnNames[] = { "Column One", "Column Two", "Column Three" };
    JTable table = new JTable(rowData, columnNames);

    JScrollPane scrollPane = new JScrollPane(table);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);

  }
}

I just wanna replace the

rowData[][]

with the information from my tables and the

columNames[]

that is all I want, I'm not sure if I'm making a big deal out of it using ArrayList and what not, Glad your helping me
:)

Okay, I think I have what you want now. This is VERY brief and simple and I've made things hard-coded that you would want to make configurable in production code. But I'm illustrating the principle here.

Remember that this is an ArrayList<Employee> and you can populate it with Employee objects in whatever way suits you best. BUT because it implements TableModel you can plug it into a JTable as it's data source. Just like you would with a Object [] [].

package storytime;

import java.util.ArrayList;
import javax.swing.event.TableModelListener;

public class EmployeeCatalog extends ArrayList<Employee> implements javax.swing.table.TableModel {
    
    private String[] colHdg = {"Id", "First Name", "Last Name"};
    private Class[] colType = {Integer.class, String.class, String.class};
    
    public int getRowCount() {
        return this.getRowCount();
    }

    public int getColumnCount() {
        return colHdg.length;
    }

    public String getColumnName(int columnIndex) {
        return colHdg [columnIndex];
    }

    public Class<?> getColumnClass(int columnIndex) {
        return colType [columnIndex];
    }

    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false /* or true if you want to implement that... */;
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        Object value = null;
        Employee row = this.get(rowIndex);
        switch (columnIndex) {
            case 0:
                value = row.getId();
                break;
            case 1:
                value = row.getfName();
                break;
            case 2:
                value = row.getlName();
                break;
        }
        return value;
    }

    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void addTableModelListener(TableModelListener l) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void removeTableModelListener(TableModelListener l) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.