So I need to make a table where all the records in my ACCESS database will reflect. The table should be editable. the table should have the basic functionalities such as ADD, EDIT and DELETE. I also need to make a search where a user can type what he/she wants to search, and then filter ther table.

I searched the net and found this tutorial but it is using sql, so when im trying to retrieve my table, it says that there are no tables taht exist.
http://www.javaguicodexample.com/javadesktopguimysql1.html

i need you to help me. thank you so much. :D

attached here is the initial screenshot of what i want..

Given the limited information nobody can be 100% sure what is wrong.
1) What database you used?
2) What driver you used?
3) What changes did you do, if any, to create database as stated in that tutorial?
4) What is exact error message?

I use Microsoft Access Database and the driver jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=<db>. In that tutorial I skipped the step "DESC tablename" because it causes me an error, so what I did is, I jumped to "SELECT * From.." and the code was executed and i saw my table in netbeans, when i was about to make the database application, the connection succeeded but the database table is grey out. it says that "Connected database doesn't contain tables."

thanks for your reply. :)

hi there again. i successfully done my table, my problem no is i am required to make it sortable. when the user clicks the header it should be automatically sorted, i also need to make the color of the rows alternating. Please help.

For coloured row you can try to use this

DefaultTableModel model = /* CREATE DefaultTableModel FROM DATA AVAILABLE TO YOU, THERE IS NUMBER OF CONSTRUCTORS YOU CAN USE*/
  JTable table = new JTable(model){
    public Component prepareRenderer(TableCellRenderer renderer,int rowIndex, int colIndex) {
      Component comp = super.prepareRenderer(renderer, rowIndex, colIndex);
      if (rowIndex % 2 == 0 && !isCellSelected(rowIndex, colIndex)) {
        comp.setBackground(Color.PINK);
      } 
      else {
        comp.setBackground(Color.WHITE);
      }
    return comp;
  }
};
commented: for safiest way as I know +8
commented: You shouldn't do their homework for them... -1

DefaultTableModel model = /* CREATE DefaultTableModel FROM DATA AVAILABLE TO YOU, THERE IS NUMBER OF CONSTRUCTORS YOU CAN USE*/

what does it mean?

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package myjava;
import java.sql.*;
import myjava.Search.*;

/**
 *
 * @author OJT
 */
public class DBEngine {
   
    String se = null;
    public Connection dbConnection()throws Exception
    {
        se = Search.jTextField1.getText();
        String database =  "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=C:/Users/OJT/Documents/db.mdb";
        return DriverManager.getConnection(database);
    }
    
    
    public void getInfo()
    {
        try {
            PreparedStatement pre = null;
            for (int ctr2 = 0; ctr2 < Search.jTable1.getColumnCount(); ctr2++) {
                for (int ctr1 = 0; ctr1 < Search.jTable1.getRowCount(); ctr1++) {
                    Search.jTable1.setValueAt("", ctr1, ctr2);
                }
            }

            Connection conn = dbConnection();
            //kung anu ung sinelect sa combobox galing sa search.java
            if (Search.jComboBox1.getSelectedItem().toString().equals("ALL")){
                pre = conn.prepareStatement("select * from Info");
            }
            else if (Search.jComboBox1.getSelectedItem().toString().equals("Last Name")){
                pre = conn.prepareStatement("select * from Info where lastname like'%" + se + "%'");
            }
            else if (Search.jComboBox1.getSelectedItem().toString().equals("First Name")){
                pre = conn.prepareStatement("select * from Info where firstname like'%" + se + "%'");
            }
            else if (Search.jComboBox1.getSelectedItem().toString().equals("Middle Initial")){
                pre = conn.prepareStatement("select * from Info where middleI like '%" + se + "%'");
            }
            else if (Search.jComboBox1.getSelectedItem().toString().equals("Date of Birth")){
                pre = conn.prepareStatement("select * from Info where age like'%" + se + "%'");
            }
            else if (Search.jComboBox1.getSelectedItem().toString().equals("Address")){
                pre = conn.prepareStatement("select * from Info where address like '%" + se + "%'");
            }
            else if (Search.jComboBox1.getSelectedItem().toString().equals("Course")){
                pre = conn.prepareStatement("select * from Info where course like'%" + se + "%'");
            }
            else if (Search.jComboBox1.getSelectedItem().toString().equals("Contact No")){
                pre = conn.prepareStatement("select * from Info where contactno like '%" + se + "%'");
            }
            else if (Search.jComboBox1.getSelectedItem().toString().equals("Position")){
                pre = conn.prepareStatement("select * from Info where position like '%" + se + "%'");
            }
            else if (Search.jComboBox1.getSelectedItem().toString().equals("Remarks")){
                pre = conn.prepareStatement("select * from Info where remarks like'%" + se + "%'");
            }
            else if (Search.jComboBox1.getSelectedItem().toString().equals("Date Applied")){
                pre = conn.prepareStatement("select * from Info where dateapplied like'%" + se + "%'");
            }
              else if (Search.jComboBox1.getSelectedItem().toString().equals("School")){
                pre = conn.prepareStatement("select * from Info where school like'%" + se + "%'");
            }
              else if (Search.jComboBox1.getSelectedItem().toString().equals("Employment Background")){
                pre = conn.prepareStatement("select * from Info where empbg like'%" + se + "%'");
            }
            
            

            ResultSet result = pre.executeQuery();
            //display result sa search.java based sa tinype sa textbox
            int rowctr = 0;
            while (result.next()) {
                Search.jTable1.setValueAt(result.getString("lastname"), rowctr, 0);
                Search.jTable1.setValueAt(result.getString("firstname"), rowctr, 1);
                Search.jTable1.setValueAt(result.getString("middleI"), rowctr, 2);
                Search.jTable1.setValueAt(result.getString("age"), rowctr, 3);
                Search.jTable1.setValueAt(result.getString("address"), rowctr, 4);
                Search.jTable1.setValueAt(result.getString("course"), rowctr, 5);
                Search.jTable1.setValueAt(result.getString("school"), rowctr, 6);
                Search.jTable1.setValueAt(result.getString("contactno"), rowctr, 7);
                Search.jTable1.setValueAt(result.getString("contactno2"), rowctr, 8);
                Search.jTable1.setValueAt(result.getString("empbg"), rowctr, 9);
                Search.jTable1.setValueAt(result.getString("position"), rowctr, 10);
                Search.jTable1.setValueAt(result.getString("dateapplied"), rowctr, 11);
                Search.jTable1.setValueAt(result.getString("remarks"), rowctr, 12);
                rowctr++;
            }
        }
        catch (Exception e) {
            //JOptionPane.showMessageDialog(se+ "NotFound"), se, se, messageType);
        }
    }
    
}

and where should i put that snippet? here is my code. thanks.

and where should i put that snippet? here is my code. thanks.

After line 78 build a proper data Collection expected by DefaultTableModel, meaning instead of looping and sending data directly to table you build up single object that you then pass to table model

commented: excelent, agreed JTable is my favorite ... +8

thanks. i will try that.
one more thing, my update button won't work. any idea? here's my code

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
             // TODO add your handling code here:
             try{
             String query1 = "UPDATE Info SET" 
                            + "lastname='"+jTable1.getValueAt(jTable1.getSelectedRow(), 1).toString()+"',"
                            + "firstname='"+jTable1.getValueAt(jTable1.getSelectedRow(), 2).toString()+"',"
                            + "middleI='"+jTable1.getValueAt(jTable1.getSelectedRow(), 3).toString()+"',"
                            + "age='"+jTable1.getValueAt(jTable1.getSelectedRow(), 4).toString()+"',"
                            + "course='"+jTable1.getValueAt(jTable1.getSelectedRow(), 5).toString()+"',"
                            + "school='"+jTable1.getValueAt(jTable1.getSelectedRow(), 6).toString()+"',"
                            + "contactno='"+jTable1.getValueAt(jTable1.getSelectedRow(), 7).toString()+"',"
                            + "contactno2='"+jTable1.getValueAt(jTable1.getSelectedRow(), 8).toString()+"' "
                            + "empbg='"+jTable1.getValueAt(jTable1.getSelectedRow(), 9).toString()+"',"
                            + "position='"+jTable1.getValueAt(jTable1.getSelectedRow(), 10).toString()+"',"
                            + "dateapplied='"+jTable1.getValueAt(jTable1.getSelectedRow(), 11).toString()+"',"
                            + "remarks='"+jTable1.getValueAt(jTable1.getSelectedRow(), 12).toString()+"',"
                            + "WHERE ID ="+jTable1.getValueAt(jTable1.getSelectedRow(), 0)+";";

                            PreparedStatement statement1 = conn.prepareStatement(query1);
                            statement1.executeUpdate();

                            JOptionPane.showMessageDialog(null, "Record Updated", "Information!", JOptionPane.INFORMATION_MESSAGE);
        
              }
    
        catch(Exception e) {
          JOptionPane.showMessageDialog(null, "Record NOT Updated", "Information!", JOptionPane.INFORMATION_MESSAGE);
        
           
        }

That is very broad request. Does it throw any errors when you execute it? Does your query works when you try it directly on database (command line or GUI tool, plus filling variable spaces)

PS: You should

  1. change that query to prepared statement as you have it in the other code sample
  2. extract row data as an object and not collection of parameters and provide some validation on it and then use it in combination with prepared statement
jTable1.getValueAt(jTable1.getSelectedRow(), 1).toString()
jTable1.getValueAt(jTable1.getSelectedRow(), 2).toString()

vs

person.getLastName()
person.getFirstName()

@peter_budo please edit your post and add test for null, because JTable hasn't problem helt null value in the TableCell, and set this value to the SQL Query isn't good idea :-)

@peter_budo, after trying to update the record, once I clicked the update button, it will go to the catch(exception e) and output this as e.message:

# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x778f7adf, pid=2440, tid=4088
#
# JRE version: 6.0_25-b06
# Java VM: Java HotSpot(TM) Client VM (20.0-b11 mixed mode, sharing windows-x86 )
# Problematic frame:
# C [ole32.dll+0x37adf]
#
# An error report file with more information is saved as:
# C:\Users\OJT\Documents\NetBeansProjects\myjava\hs_err_pid2440.log
#
# If you would like to submit a bug report, please visit:
# http://java.sun.com/webapps/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at myjava.Search.jButton3MouseClicked(Search.java:363)
	at myjava.Search.access$500(Search.java:28)
	at myjava.Search$7.mouseClicked(Search.java:264)
	at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:253)
	at java.awt.Component.processMouseEvent(Component.java:6291)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
	at java.awt.Component.processEvent(Component.java:6053)
	at java.awt.Container.processEvent(Container.java:2041)
	at java.awt.Component.dispatchEventImpl(Component.java:4651)
	at java.awt.Container.dispatchEventImpl(Container.java:2099)
	at java.awt.Component.dispatchEvent(Component.java:4481)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4247)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
	at java.awt.Container.dispatchEventImpl(Container.java:2085)
	at java.awt.Window.dispatchEventImpl(Window.java:2478)
	at java.awt.Component.dispatchEvent(Component.java:4481)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:643)
	at java.awt.EventQueue.access$000(EventQueue.java:84)
	at java.awt.EventQueue$1.run(EventQueue.java:602)
	at java.awt.EventQueue$1.run(EventQueue.java:600)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
	at java.awt.EventQueue$2.run(EventQueue.java:616)
	at java.awt.EventQueue$2.run(EventQueue.java:614)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:613)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

this is the error for my delete button. :( please help me.

Delete operation : Error is explicit, you provided object/variable that hasn't been initialized and is therefore null. Error occurred on line Search.java line 363
Update operation : An error report file with more information is saved as:
C:\Users\OJT\Documents\NetBeansProjects\myjava\hs_err_pid2440.log
So you need to read that log file or provide code. Did you changed that query to prepared statement? Did you tried to execute query directly on DB as I asked you to do?

I tried executing the query directly to my DB. It does not change anything.
What do you mean by " Did you changed that query to prepared statement?
How can I fix this?
I'm really having troubles. Sorry and thanks again :)

@mKorbel - test for null?

Sorry I just spotted that you actually use PreparedStatement in both cases but you are using it wrong way. You still try to inject variables directly into SQL query while building string.
Something like this is error prone, you can easily mismatch opening and closing single or double quotes, or forget to include plus sign

String query1 = "UPDATE Info SET" 
                            + "lastname='"+jTable1.getValueAt(jTable1.getSelectedRow(), 1).toString()+"',"
                            + "firstname='"+jTable1.getValueAt(jTable1.getSelectedRow(), 2).toString()+"',"
                            + "middleI='"+jTable1.getValueAt(jTable1.getSelectedRow(), 3).toString()+"',"
                            + "age='"+jTable1.getValueAt(jTable1.getSelectedRow(), 4).toString()+"',"
                            + "course='"+jTable1.getValueAt(jTable1.getSelectedRow(), 5).toString()+"',"
                            + "school='"+jTable1.getValueAt(jTable1.getSelectedRow(), 6).toString()+"',"
                            + "contactno='"+jTable1.getValueAt(jTable1.getSelectedRow(), 7).toString()+"',"
                            + "contactno2='"+jTable1.getValueAt(jTable1.getSelectedRow(), 8).toString()+"' "
                            + "empbg='"+jTable1.getValueAt(jTable1.getSelectedRow(), 9).toString()+"',"
                            + "position='"+jTable1.getValueAt(jTable1.getSelectedRow(), 10).toString()+"',"
                            + "dateapplied='"+jTable1.getValueAt(jTable1.getSelectedRow(), 11).toString()+"',"
                            + "remarks='"+jTable1.getValueAt(jTable1.getSelectedRow(), 12).toString()+"',"
                            + "WHERE ID ="+jTable1.getValueAt(jTable1.getSelectedRow(), 0)+";";

where clean query declaration and then providing parameters is far better and more readable

String query1 = "UPDATE Info SET lastname=?, firstname=?, middleI=?, age=?, course=?, school=?, contactno=?, contactno2=?, empbg=?, position=?, dateapplied=?, remarks=? WHERE ID =?";
preparedStatement = conn.prepareStatement(query1);
preparedStatement.setString(1,person.getLasttName());
preparedStatement.setString(2, person.getFirstName());
preparedStatement.setString(3, person.getMiddleI());
preparedStatement.setString(4, person.getAge());
preparedStatement.setString(5, person.getCourse());
preparedStatement.setString(6, person.getSchool());
preparedStatement.setString(7, person.getContactNo());
preparedStatement.setString(8,person.getContactNo2());
preparedStatement.setString(9,person.empbg);
preparedStatement.setString(10,person.getPosition());
preparedStatement.setString(11,person.getDateApplied());
preparedStatement.setString(12,person.getRemarks());
preparedStatement.setString(13,person.getID());

As for mKorbel request to check for null, what he is trying to say is did you validated your form before your try to update database? Are you getting everything from form correctly? Are user provided data valid?(any case of cell returning null value)

my table is running okay. when clicked the button All. All records from the database are returned. The filter of the table is also working. Okay I will your codes and hopefully it will work. Thanks again. :)

It's now working properly. :) Thanks for your help. Now I'm working on the alternating row colors. Thanks a lot. :)

I'm reading a lot about Cell Renderer but I really don't know how to use it or where should I put my codes. and what is a tablemodel. i found this codes in the internet

JTable table = new JTable(){
    public Component prepareRenderer(TableCellRenderer renderer, int row, int column){
        Component returnComp = super.prepareRenderer(renderer, row, column);
        Color alternateColor = new Color(252,242,206);
        Color whiteColor = Color.WHITE;
        if (!returnComp.getBackground().equals(getSelectionBackground())){
            Color bg = (row % 2 == 0 ? alternateColor : whiteColor);
            returnComp .setBackground(bg);
            bg = null;
        }
        return returnComp;
};

i just copy paste it in my program, there were no errors but it does not make any changes in my table. This will be the last thing that I need for my project. it would be a great help if you will help me again. Thank you and I owe you bigtime. :)

thanks :)

you're welcome

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.