4

I'm currently developing a program in the NetBeans IDE. I have created a nice GUI and I have created my MS Access Database. I am having trouble in displaying MS Access data in JTable. I would like to avoid the use of vectors, as shown in most of the tutorials, I found on the internet, as I am still in High school and this knowledge is beyond me.

Any pointers in the right direction will be immensely appreciated!

Here is my code:

 String[] columnNames = {"First Name",
                              "Last Name",
                               "Category",
                               "Amount"
                               };
  Object[] row =new Object[4];
  JLabel lbl=new JLabel("Add New Property");
  lbl.setBounds(100,200,200,100);
  lbl.setVisible(true);
  invntryfrm.add(lbl);
  //invntryfrm.setVisible(true);
  JPanel panel=new JPanel();
  panel.setBounds(20,200,680,100);
  panel.setBackground(Color.WHITE);
  invntrybck.add(panel);
  DefaultTableModel model=new DefaultTableModel();
  model.setColumnIdentifiers(columnNames);
  JTable tabel=new JTable();
  tabel.setBounds(100,20,700,400);
  tabel.setBackground(Color.DARK_GRAY);
  tabel.setForeground(Color.WHITE);
  tabel.setModel(model);
  tabel.setPreferredScrollableViewportSize(new Dimension(500,50));
  tabel.setFillsViewportHeight(true);
  JScrollPane pane=new JScrollPane(tabel);
  panel.add(pane);
  try{
  Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\MUHAMMAD SHAHAB\\real estate.accdb");
  String sql="select Username,Password,Country,City from simba";
  PreparedStatement pst=conn.prepareStatement(sql);
  ResultSet rs=pst.executeQuery();

   }
   catch(Exception ex)
   {
       JOptionPane.showMessageDialog(null, ex);
   }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Mcolo
  • 149
  • 2
  • 10
  • Refer answer given @ http://stackoverflow.com/questions/27679867/jtable-how-to-use-rs2xml You need to use rs2xml.jar. It is the easiest way to render resultset in a jTable. – Ganesh S Oct 01 '16 at 09:34
  • 1
    *"I am having trouble.."* What trouble, exactly? Can you retrieve the data in a command line app.? Can you create a table from hard coded data? Now is a good time for more detail, not less. General tips: 1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. .. – Andrew Thompson Oct 01 '16 at 10:07
  • 1
    .. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 3) I'd add the table at star-up and simply create and set the model once the DB enquiry is performed. Adding components after the GUI is created presents it's own set of challenges. – Andrew Thompson Oct 01 '16 at 10:07

3 Answers3

6

(1).First add rs2Xml.jar in your library folder and then do the following change in your code:

 Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\MUHAMMAD SHAHAB\\real estate.accdb");
                               String sql="select Username,Password,Country,City from simba";
                               PreparedStatement pst=conn.prepareStatement(sql);
                               ResultSet rs=pst.executeQuery();
                               tabel.setModel(DbUtils.resultSetToTableModel(rs)); 

I hope this will work fine for you.

Shahab Khan
  • 542
  • 2
  • 10
2
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;

import static java.lang.System.out;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.sql.Statement;

import javax.swing.JFrame;

import javax.swing.JScrollPane;

import javax.swing.JTable;

import javax.swing.table.DefaultTableModel;

public class JavaApplication16 {



public static void main(String[] args) {


    String driver="org.apache.derby.jdbc.ClientDriver";
    String url="jdbc:derby://localhost:1527/simbadb";
    String username="simbadb", password="simbadb";

    Connection con=null;
    try
    {
        Class.forName(driver);
        con=DriverManager.getConnection(url, username, password);
        String query="select * from simba";
        Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);

        int rowcount=0;
        ResultSet rs=stmt.executeQuery(query);
        ResultSetMetaData rsmd=rs.getMetaData();
        int columncount=rsmd.getColumnCount();

        while(rs.next())
        {
            rowcount++;
        }
        out.println("number of records: "+rowcount);

        String[][] rowdata=new String[rowcount][columncount];
        rs.beforeFirst();
        int rowindex=0;
        while(rs.next())
        {
            int columnindex=0;
            for(int i=1;i<=columncount;i++)
            {
                rowdata[rowindex][columnindex]=rs.getString(i);
                columnindex++;
            }
            rowindex++;
        }

        String[] coldata=new String[columncount];
        int colindex=0;
        for(int i=1;i<=columncount;i++)
        {
            coldata[colindex]=rsmd.getColumnName(i);
            colindex++;
        }
        rs.close();

        DefaultTableModel dtm=new DefaultTableModel(rowdata, coldata);

        JFrame frame=new JFrame();

        JTable table=new JTable();
        table.setModel(dtm);

        Container c=frame.getContentPane();
       c.setLayout(new FlowLayout(FlowLayout.LEFT));
       c.add(new JScrollPane(table));

       frame.setSize(new Dimension(500, 500));
       frame.setVisible(true);
    }
    catch(Exception e)
    {
        out.println(e);
    }
    finally
    {
        try
        {
            if(con!=null)
            {
                con.close();
                out.println("closed");
            }
        }
        catch(Exception e)
        {
            out.println(e);
        }


    }

}

}


In jdk 8 JdbcOdbcDriver is not supported and removed! so I have to test it in derby database.
netbeans also works as ide for derby database so you can use that
I have used arrays in place of vector or any collection type! hope it may be easy for you to understand.
DefaultTableModel is a class that inherits TableModel interface. actually the swing components are based on MVC architecture where there is Model interface for every component.
DefaultTableModel class is contract/provider class of TableModel interface and contains overloaded constructors that is used to populate row and column data into it.
hope you understand my notes! if any problem then plz feel free to mail me at:
alkaramansari1@gmail.com
0

just add
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
in the try Catch Block