Problem ResultSet in JTable  ( - -)""

I have encountered error when compile the code implemented, as i first time write Jtable, it might be a bit messy.
Please advice ..............
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import javax.swing.JTable;
import java.util.*;
import java.io.*;
public class display {
static Statement stmt;
static Connection conn = null;
String msg="Err";
static int c=0;
static String str;
static boolean scrolling= true;
static Statement stat;
static JScrollPane scrollPane;
static ResultSet set;
static ResultSetMetaData rsmd;
static String[] tableColumnsName;
private ArrayList cache;
public void open() {
try {
conn = DB.getConnection();
stmt = conn.createStatement();
} catch(SQLException e) {
System.out.println(e);
public static void main(String[] args)
display dis = new display();
dis.open();
dis.display();
dis.CachingResultSetTableModel();
int r= dis.getRowCount();
Object data=dis.getValueAt (r ,c);
JTable table = new JTable(data,tableColumnsName);
dis.close();
public static void display() {
try {
String st="";
String str="";
ResultSet set = stmt.executeQuery("select * from SYSTEM_USER");
DatabaseMetaData meta= conn.getMetaData();
rsmd= set.getMetaData();
c= getColumnCount();
tableColumnsName= new String[c];
while(set.next()) {
for(int i= 0; i<c; i++)
     tableColumnsName=getColumnName(i);
System.out.println(str);
} catch(SQLException e) {
System.out.println(e);
public static String getColumnName(int c)
try
return rsmd.getColumnName(c+1);
catch(SQLException e)
e.printStackTrace();
return "";
public static int getColumnCount()
try
return rsmd.getColumnCount();
catch(SQLException e)
e.printStackTrace();
return 0;
public void close() {
try {
stmt.close();
} catch(SQLException e) {
System.out.println(e);
try {
conn.close();
} catch(SQLException e) {
System.out.println(e);
public void CachingResultSetTableModel()
try
cache = new ArrayList();
/* place all data in an array list of Object[] arrays
We don't use an Object[][] because we don't know
how many rows are in the result set
while (set.next())
Object[] row = new Object[c];
for (int j = 0; j < row.length; j++)
row[j] = set.getObject(j + 1);
cache.add(row);
catch(SQLException e)
System.out.println("Error " + e);
public Object getValueAt(int r, int c)
if (r < cache.size())
return ((Object[])cache.get(r))[c];
else
return null;
public int getRowCount()
return cache.size();

Its seems like get object no work in my db, the object sound like null.
how i go to extract table data???
Error message
C:\Proj>javac display.java
Note: display.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: display.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
C:\Proj>java display
Exception in thread "main" java.lang.NullPointerException
at display.CachingResultSetTableModel(display.java:143)
at display.main(display.java:42)
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import javax.swing.JTable;
import java.util.*;
import java.io.*;
public class display extends JFrame {
    static Statement stmt;
    static Connection conn = null;
    String msg="Err";
    static int c=0;
    static String str;
    static boolean scrolling= true;
    static Statement stat;
    static JScrollPane scrollPane;
    static ResultSet set;
    static ResultSetMetaData rsmd;
    static String[] tableColumnsName;
    static Vector<Object> cache;
    static JTable table;
   public void open() {
        try {
            conn = DB.getConnection();
            stmt = conn.createStatement();
        } catch(SQLException e) {
            System.out.println(e);
   public static void main(String[] args)
        display dis = new display();
        JFrame frame= new display();
        dis.open();
        dis.display();
        dis.CachingResultSetTableModel();         
        int r= dis.getRowCount();
        Object data=dis.getValueAt (r ,c);
        Vector<Object> newColumnNames = new Vector();
        for(int i=0; i<tableColumnsName.length; i++)
                newColumnNames.add(tableColumnsName);
table = new JTable(cache,newColumnNames);
frame.show();
dis.close();
public void display() {
try {
String st="";
String str="";
ResultSet set = stmt.executeQuery("select * from SYSTEM_USER");
DatabaseMetaData meta= conn.getMetaData();
rsmd= set.getMetaData();
c= getColumnCount();
tableColumnsName= new String[c];
while(set.next()) {
for(int i=0; i<c; i++)
          tableColumnsName[i]=getColumnName(i);
} catch(SQLException e) {
System.out.println(e);
getContentPane().add(new JScrollPane(table));
public static String getColumnName(int c)
try
return rsmd.getColumnName(c+1);
catch(SQLException e)
e.printStackTrace();
return "";
public static int getColumnCount()
try
return rsmd.getColumnCount();
catch(SQLException e)
e.printStackTrace();
return 0;
public void close() {
try {
stmt.close();
} catch(SQLException e) {
System.out.println(e);
try {
conn.close();
} catch(SQLException e) {
System.out.println(e);
public void CachingResultSetTableModel()
try
cache = new Vector();
/* place all data in an array list of Object[] arrays
We don't use an Object[][] because we don't know
how many rows are in the result set
while (set.next())
//create a Vector to hold the data for a single row
Vector<Object> row = new Vector();
//add the column data to the row
for(int i=0; i<tableColumnsName.length; i++)
row.add(set.getObject(i+1));
//add the row data to the Vector for the table rows
cache.add(row);
catch(SQLException e)
System.out.println("Error " + e);
public Object getValueAt(int r, int c)
if (r < cache.size())
return ((Object[])cache.get(r))[c];
else
return null;
public int getRowCount()
return cache.size();

Similar Messages

  • Problem printing the JTable

    Hi all,
    I have a problem with printing JTable.
    My application has a submit button,JTable and Print Button.
    As I click on the Submit button, the data is retrieved from the Database(MS Access) and displayed on the JTable.
    Now when I click on the Print button, the printer properties dialog box is displayed. But when I click on the print button in the dialog box, nothing is printed on the paper.
    I checked the printers and faxes in the control panel, It showed Java printing under the Document name and Printing under the Status. It is displayed for sometime and then disappeared after some time. But nothing is printed on the paper(not even the blank paper).
    I tried a lot but couldn't understand the problem.
    I have used the following files:
    PrintJTable.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import java.awt.geom.*;
    import java.awt.Dimension;
    import java.applet.*;
    import java.sql.*;
    import java.util.*;
    import java.net.*;
    import java.lang.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    class PrintJTable implements ActionListener,Printable
    Connection connect;
    ResultSet rs;
    JTable table;
    JScrollPane tableAggregate;
    DisplayTable displayTable;
    JButton print,submitButton;
    public PrintJTable()
    JFrame frame = new JFrame("Table");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}});
    connect();
    displayTable= new DisplayTable();
    JButton submitButton= new JButton("SUBMIT");
    submitButton.addActionListener(this);
    JButton printButton= new JButton("PRINT!");
    // for faster printing turn double buffering off
    RepaintManager.currentManager( frame).setDoubleBufferingEnabled(false);
    printButton.addActionListener( new ActionListener(){
    public void actionPerformed(ActionEvent evt) {
    PrinterJob pj=PrinterJob.getPrinterJob();
    pj.setPrintable(PrintJTable.this);
    pj.printDialog();
    try{
    pj.print();
    }catch (Exception PrintException) {}
    tableAggregate = createTable();
    tableAggregate.setBorder(new BevelBorder(BevelBorder.LOWERED));
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(submitButton,BorderLayout.NORTH);
    frame.getContentPane().add(tableAggregate,BorderLayout.CENTER);
    frame.getContentPane().add(printButton,BorderLayout.SOUTH);
    frame.pack();
    frame.setVisible(true);
    } // end of constructor
    public void connect()
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("Opening db connection");
    connect = DriverManager.getConnection("jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=C:/db1.mdb","","");
    catch (ClassNotFoundException ex) {
    System.err.println("Cannot find the database driver classes.");
    System.err.println(ex);
    catch (SQLException ex) {
    System.err.println("Cannot connect to this database.");
    System.err.println(ex);
    public JScrollPane createTable() {
    displayTable= new DisplayTable();
    JTable table = new JTable(displayTable);
         table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
         table.getTableHeader().setReorderingAllowed(false);
    JScrollPane scrollpane = new JScrollPane(table,
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
    JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    return scrollpane;
    } // end of createTable()
    public void actionPerformed(ActionEvent ie)
    try
    Statement statement6=connect.createStatement();
    ResultSet rs6=statement6.executeQuery("select * from benf_details");
    displayTable.executeQuery(rs6);
    statement6.close();
    catch(SQLException sqle)
    JOptionPane.showMessageDialog(null,"error2"+sqle);
    }// end of actionPerformed
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
    Graphics2D g2 = (Graphics2D)g;
    g2.setColor(Color.black);
    int fontHeight=g2.getFontMetrics().getHeight();
    int fontDesent=g2.getFontMetrics().getDescent();
    double pageHeight = pageFormat.getImageableHeight()-fontHeight; //leave room for page number
    double pageWidth = pageFormat.getImageableWidth();
    System.out.println("page width = " + pageWidth );
    double tableWidth = (double) table.getColumnModel().getTotalColumnWidth();
    System.out.println("table width = " + tableWidth );
    double scale = 1;
    if (tableWidth >= pageWidth) {
    scale = pageWidth / tableWidth;
    System.out.println("scale = " + scale );
    double headerHeightOnPage = table.getTableHeader().getHeight() * scale;
    double tableWidthOnPage = tableWidth * scale;
    double oneRowHeight = (table.getRowHeight() + table.getRowMargin()) * scale;
    int numRowsOnAPage = (int)((pageHeight - headerHeightOnPage) / oneRowHeight);
    double pageHeightForTable = oneRowHeight * numRowsOnAPage;
    int totalNumPages = (int)Math.ceil(((double)table.getRowCount())/numRowsOnAPage);
    if(pageIndex >= totalNumPages) {
    return NO_SUCH_PAGE;
    g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    g2.drawString("Page: "+ (pageIndex + 1),(int)pageWidth / 2 - 35,
    (int)( pageHeight + fontHeight - fontDesent ));//bottom center
    g2.translate( 0f, headerHeightOnPage );
    g2.translate( 0f, -pageIndex * pageHeightForTable );
    //If this piece of the table is smaller than the size available,
    //clip to the appropriate bounds.
    if (pageIndex + 1 == totalNumPages) {
    int lastRowPrinted = numRowsOnAPage * pageIndex;
    int numRowsLeft = table.getRowCount() - lastRowPrinted;
    g2.setClip(0, (int)(pageHeightForTable * pageIndex),
    (int) Math.ceil(tableWidthOnPage),
    (int) Math.ceil(oneRowHeight * numRowsLeft));
    //else clip to the entire area available.
    else{
    g2.setClip(0, (int)(pageHeightForTable * pageIndex),
    (int) Math.ceil(tableWidthOnPage),
    (int) Math.ceil(pageHeightForTable));
    g2.scale(scale,scale);
    table.paint(g2);
    g2.scale(1/scale,1/scale);
    g2.translate( 0f, pageIndex * pageHeightForTable);
    g2.translate( 0f, -headerHeightOnPage);
    g2.setClip(0, 0,(int) Math.ceil(tableWidthOnPage), (int)Math.ceil(headerHeightOnPage));
    g2.scale(scale,scale);
    table.getTableHeader().paint(g2);//paint header at top
    return Printable.PAGE_EXISTS;
    } // end of print()
    public static void main(String[] args) {
    new PrintJTable();
    }// end of PrintJTable
    DisplayTable.java
    import java.util.Vector;
    import java.sql.*;
    import javax.swing.*;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.event.TableModelEvent;
    public class DisplayTable extends AbstractTableModel {
    Connection connection;
    Statement statement;
    ResultSet resultSet;
    String[] columnNames = {};
    Vector          rows = new Vector();
    ResultSetMetaData metaData;
    String db_uname,db_passwd;
    public DisplayTable() {
    public void executeQuery(ResultSet resultSet) {
    try {
    metaData = resultSet.getMetaData();
    int numberOfColumns = metaData.getColumnCount();
    columnNames = new String[numberOfColumns];
    // Get the column names and cache them.
    // Then we can close the connection.
    for(int column = 0; column < numberOfColumns; column++) {
    columnNames[column] = metaData.getColumnLabel(column+1);
    // Get all rows.
    rows = new Vector();
    while (resultSet.next()) {
    Vector newRow = new Vector();
    for (int i = 1; i <= getColumnCount(); i++) {
         newRow.addElement(resultSet.getObject(i));
    rows.addElement(newRow);
    // close(); Need to copy the metaData, bug in jdbc:odbc driver.
    fireTableChanged(null); // Tell the listeners a new table has arrived.
    catch (SQLException ex) {
    System.err.println(ex);
    public void close() throws SQLException {
    System.out.println("Closing db connection");
    resultSet.close();
    statement.close();
    connection.close();
    protected void finalize() throws Throwable {
    close();
    super.finalize();
    // Implementation of the TableModel Interface
    // MetaData
    public String getColumnName(int column) {
    if (columnNames[column] != null) {
    return columnNames[column];
    } else {
    return "";
    public Class getColumnClass(int column) {
    int type;
    try {
    type = metaData.getColumnType(column+1);
    catch (SQLException e) {
    return super.getColumnClass(column);
    switch(type) {
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    return String.class;
    case Types.BIT:
    return Boolean.class;
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    return Integer.class;
    case Types.BIGINT:
    return Long.class;
    case Types.FLOAT:
    case Types.DOUBLE:
    return Double.class;
    case Types.DATE:
    return java.sql.Date.class;
    default:
    return Object.class;
    // to make the cells editable
    public boolean isCellEditable(int row, int column) {
    try {
    return metaData.isWritable(column+1);
    catch (SQLException e) {
    return false;
    public int getColumnCount() {
    return columnNames.length;
    // Data methods
    public int getRowCount() {
    return rows.size();
    public Object getValueAt(int aRow, int aColumn) {
    Vector row = (Vector)rows.elementAt(aRow);
    return row.elementAt(aColumn);
    public String dbRepresentation(int column, Object value) {
    int type;
    if (value == null) {
    return "null";
    try {
    type = metaData.getColumnType(column+1);
    catch (SQLException e) {
    return value.toString();
    switch(type) {
    case Types.INTEGER:
    case Types.DOUBLE:
    case Types.FLOAT:
    return value.toString();
    case Types.BIT:
    return ((Boolean)value).booleanValue() ? "1" : "0";
    case Types.DATE:
    return value.toString(); // This will need some conversion.
    default:
    return "\""+value.toString()+"\"";
    public void setValueAt(Object value, int row, int column) {
    try {
    String tableName = metaData.getTableName(column+1);
    // Some of the drivers seem buggy, tableName should not be null.
    if (tableName == null) {
    System.out.println("Table name returned null.");
    String columnName = getColumnName(column);
    String query =
    "update "+tableName+
    " set "+columnName+" = "+dbRepresentation(column, value)+
    " where ";
    // We don't have a model of the schema so we don't know the
    // primary keys or which columns to lock on. To demonstrate
    // that editing is possible, we'll just lock on everything.
    for(int col = 0; col<getColumnCount(); col++) {
    String colName = getColumnName(col);
    if (colName.equals("")) {
    continue;
    if (col != 0) {
    query = query + " and ";
    query = query + colName +" = "+
    dbRepresentation(col, getValueAt(row, col));
    System.out.println(query);
    System.out.println("Not sending update to database");
    // statement.executeQuery(query);
    catch (SQLException e) {
    // e.printStackTrace();
    System.err.println("Update failed");
    Vector dataRow = (Vector)rows.elementAt(row);
    dataRow.setElementAt(value, column);
    }

    Java 1.5 incorporates a very simple way to print from a JTable. I am using a mysql DB but it is the same concept. Review my code and let me know if you have any questions.
    package emsmain;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.*;
    import java.sql.*;
    import java.text.MessageFormat;
    import java.util.*;
    import javax.print.*;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.print.attribute.PrintRequestAttributeSet;
    import javax.swing.*;
    import javax.swing.JTable;
    import javax.swing.table.*;
    import java.awt.print.*;
    public class TableFromDatabase extends JFrame implements ActionListener{
        JButton jbtprint = new JButton("Print Report");
        JTable Reporttable;
        Connection conn = Connect_Database.getConnection();
         public TableFromDatabase()
    Vector columnNames = new Vector();
    Vector data = new Vector();     
              try{  
                String query = null;
                Statement ps = null;
                ResultSet rs = null;
                  //Class Master List
                  if (Report_Menu.jrbMaster_list.isSelected()){
                      query =("Select * from students") ;
                  //Classes taken by student
                  if (Report_Menu.jrbClass_taken.isSelected()){
                      String taken = Report_Menu.jtfStudent.getText();
                      query = ("select program.course_num, course_name, course_start_date, course_stat_desc from registration, program where student_id = '"+taken+"' and program.course_num = registration.course_num");
                  //Birthday report
                  if (Report_Menu.jrbBirthday.isSelected()){
                      String birthday = (String) Report_Menu.jcb_birthday.getSelectedItem();
                      query = ("SELECT student_id, fname, lname, address, city, state_name, zipcode, dob FROM students where substring(dob, 6,2) = '"+birthday+"'"); 
                  //Course Catologue
                  if (Report_Menu.jrbCourseCatologue.isSelected()){
                      String course = (String) Report_Menu.jcbChooseCourse.getSelectedItem();
                      query = ("select  course_name, course_length, course_cost, course_credits from course where course_name = '"+course+"'");
                  //Certification expiration report
                  if (Report_Menu.jrbExpiration.isSelected()){
                      String month = (String) Report_Menu.jcbMonth.getSelectedItem();
                      String year = (String) Report_Menu.jcbYear.getSelectedItem();
                      query = ("SELECT FNAME, LNAME FROM STUDENTS, REGISTRATION WHERE substring(expiration_date, 6,2) = '"+month+"' and substring(expiration_date, 1,4) = '"+year+"' and registration.student_id = students.student_id") ;
                  //Class Roster
                  if (Report_Menu.jrbRoster.isSelected()){
                      String c_number = Report_Menu.jtfClassNumber.getText();
                      query = ("Select course_name, course_start_date, fname, lname from program, registration, students where program.course_num = '"+c_number+"' and registration.student_id = students.student_id;");
                  //Squad list and counts
                  if (Report_Menu.jrbSquadCount.isSelected()){
                      query = ("SELECT Squad_Name, count(student_id) from students group by Squad_Name");
                  //Student List
                  if (Report_Menu.jrbStudent_list.isSelected()){
                      String Choose_month = (String) Report_Menu.jcbcourse_month.getSelectedItem();
                      String Choose_Course = (String) Report_Menu.jcbcourse_name.getSelectedItem();
                      query = ("select count(student_id) from (registration, program) where program .course_name = '"+Choose_Course+"' and substring(course_start_date, 6,2) = '"+Choose_month+"'and registration.course_num = program.course_num;");
                ps = conn.createStatement();
                //Run Selected Report
                ps.execute(query);
                rs = ps.executeQuery(query);
                ResultSetMetaData md = rs.getMetaData();
                int columns = md.getColumnCount();
                //  Get column names
                for (int i = 1; i <= columns; i++)
                    columnNames.addElement( md.getColumnName(i) );
                //  Get row data
                while (rs.next())
                    Vector row = new Vector(columns);
                    for (int i = 1; i <= columns; i++)
                        row.addElement( rs.getObject(i) );
                    //add row data to JTable
                    data.addElement( row );
                rs.close();
                ps.close();
            catch(Exception e)
                JOptionPane.showMessageDialog(null,e.getMessage());
            //  Create Jtable with database data 
            Container c = getContentPane();
            c.setLayout(new BorderLayout());
            Reporttable = new JTable(data, columnNames);
            JScrollPane scrollPane = new JScrollPane( Reporttable );
            c.add( scrollPane );
            JPanel buttonPanel = new JPanel();
            buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
            buttonPanel.add(jbtprint);
            c.add(buttonPanel,BorderLayout.SOUTH);
            jbtprint.addActionListener(this);
        public void actionPerformed(ActionEvent e){
             if(e.getActionCommand().equals("Print Report")){
               PrintForm();
    public void PrintForm(){ 
         try {
             String name = null;
             // Will display correct heading for print job
             if (Report_Menu.jrbMaster_list.isSelected()){
             name = "Master List";
             if (Report_Menu.jrbBirthday.isSelected()){
             name = "Birthday List";
             if (Report_Menu.jrbClass_taken.isSelected()){
             name = "Classes taken by Student";
             if (Report_Menu.jrbCourseCatologue.isSelected()){
             name = "Course Catalogue";
             if (Report_Menu.jrbExpiration.isSelected()){
             name = "Certification Expiration Report";
             if (Report_Menu.jrbRoster.isSelected()){
             name = "Class Roster";
             if (Report_Menu.jrbSquadCount.isSelected()){
             name = "Squad list with Student Counts";
             if (Report_Menu.jrbStudent_list.isSelected()){
             name = "Student count by Course";
             // fetch the printable
             Printable printable = Reporttable.getPrintable(JTable.PrintMode.FIT_WIDTH,
                                                      new MessageFormat(name),
                                                      new MessageFormat("Page - {0}"));
             // fetch a PrinterJob
             PrinterJob job = PrinterJob.getPrinterJob();
             // set the Printable on the PrinterJob
             job.setPrintable(printable);
             // create an attribute set to store attributes from the print dialog
             PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
             // display a print dialog and record whether or not the user cancels it
             boolean printAccepted = job.printDialog(attr);
             // if the user didn't cancel the dialog
             if (printAccepted) {
                    try {
                          // do the printing (may need to handle PrinterException)
                        job.print(attr);
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
         } finally {
             // restore the original table state here (for example, restore selection)
    }

  • Problem in Customising JTable's Functionality

    Problem Scenario :
    We are facing a problem related to JTables. In our GUI, we have used JTables and the data model that we are using for the table is a bit complicated. Complicated in the sense that we want different values(multiple) in each cell of a particular column in the table and we want to use JComboBox at that particular cell. For achieving this we have set the values in the JComboBox in its renderer class. But to set the user selected value in the particular cell JComboBox we initialized a new JComboBox in the renderer class. With this the GUI is working fine but it has raised a problem that if we renderer the component another JComboBox appears in the same cell. The problem is obvious as we are initializing a new JComboBox in the renderer class, but to solve our purpose we don�t have another way.
    With the kind of data model we are using is it possible to create a JTable with combo boxes in a particular cell having different option values in each cell?
    Could someone suggest a solution for this problem?
    Regards
    Prajkta Bonde
    [email protected]

    I have done it around 4 years back. Add filled JComboBox as table data.
    Attached sample code should help
    // Imports
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    class SimpleTableExample
              extends      JFrame
         // Instance attributes used in this example
         private     JPanel          topPanel;
         private     JTable          table;
         private     JScrollPane scrollPane;
         // Constructor of main frame
         public SimpleTableExample()
              // Set the frame characteristics
              setTitle( "Simple Table Application" );
              setSize( 300, 200 );
              setBackground( Color.gray );
              // Create a panel to hold all other components
              topPanel = new JPanel();
              topPanel.setLayout( new BorderLayout() );
              getContentPane().add( topPanel );
              // Create columns names
              String columnNames[] = { "Column 1", "Column 2", "Column 3" };
              Object dataValues[][] = new Object[10][3];
              for(int row=0;row<dataValues.length;row++) {
                   for(int col=0;col<dataValues[row].length;col++){
                        JComboBox tempBox = new JComboBox();
                        for(int data=0;data<10;data++){
                             tempBox.addItem("Row "+row+" Column "+col+" Data "+data);
                        dataValues[row][col]=tempBox;
              // Create a new table instance
              table = new JTable( dataValues, columnNames );
            comboBoxColumn(table.getColumnModel().getColumn(0));
            comboBoxColumn(table.getColumnModel().getColumn(1));
            comboBoxColumn(table.getColumnModel().getColumn(2));
              // Add the table to a scrolling pane
              scrollPane = new JScrollPane( table );
              topPanel.add( scrollPane, BorderLayout.CENTER );
        public void comboBoxColumn(TableColumn comboBoxCol) {
            comboBoxCol.setCellEditor(new TableComponentEditor());
            comboBoxCol.setCellRenderer(new TableComponentRenderer());
            //Set up tool tip for the sport column header.
            TableCellRenderer headerRenderer = comboBoxCol.getHeaderRenderer();
            if (headerRenderer instanceof DefaultTableCellRenderer) {
                 ((DefaultTableCellRenderer)headerRenderer).setToolTipText("Click the sport to see a list of service stations");
        } //end of method
        class TableComponentEditor extends DefaultCellEditor {
            * Constructor
            * @param none
            TableComponentEditor() {
                super(new JComboBox());
            * Called when table Cell is clicked
            * @param table
            * @param value - Object associated with the particular column for which it is called
            * @param isSelected -whether the particular cell is selected
            * @param row - The row to which cell belongs
            * @param column - The Column To which Cell Belongs
            public  Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
                cbo = (JComboBox)value;
                return cbo;
            *  getCellEditorValue
            * @return Object
            public Object getCellEditorValue() {
                return cbo;
            /***************CLASS VARIABLES***********************/
            private JComboBox cbo = null;
        class TableComponentRenderer  implements TableCellRenderer {
            public  Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)  {
                return (JComboBox)value;
         // Main entry point for this example
         public static void main( String args[] )
              // Create an instance of the test application
              SimpleTableExample mainFrame     = new SimpleTableExample();
              mainFrame.setVisible( true );
    }

  • Problems with a JTable

    Hello folks,
    i got two problems with a JTable.
    1. how do I change the size of a table header???
    2. I know that it is possible to set different column-sizes. The problem in my table is that I don't know how long some cells are. In this case, I want to to get the biggest cell of one column and set its size as the default size of that specific column.
    Is that possilbe?
    Hopefully you can help me out,
    thank you

    A JTableHeader is just another Component, so you ought to be able to set its size like you would
    any other component; however, since its function is to act as a header for a table, it might constrain
    itself to fit the table.
    In order to size the column to fit the largest cell, for each row, go through each column and get the
    renderer component for that column (which configures the component for rendering) and get the width
    of that component. If that's bigger than the column's current width, set its width and preferred width.
    You'll also want to check the renderer component width for the header to make sure the header doesn't
    get truncated if the column doesn't have a cell whose value is longer than the header.
    : jay

  • Problem in populating jtable data from database

    hi,
    i am using JTable to retrieve data from database and show it in table. JTable
    is working fine with static data. but while retrieving from databse its giving a NullPointerException at getColumnClass() method. Below is complete source code. plzz help.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.sql.*;
    import javax.swing.table.*;
    /*jdbc connection class*/
    class connect
    Connection con;
    Statement stat;
    public connect()throws Exception
    Class.forName("org.postgresql.Driver");
    con=DriverManager.getConnection("jdbc:postgresql://localhost/dl","dl","dl");
    stat=con.createStatement();
    public ResultSet rsf(String rsstr)throws Exception
    ResultSet rs=stat.executeQuery(rsstr);
    return rs;
    public void upf(String upstr)throws Exception
    stat.executeUpdate(upstr);
    class MyTableModel extends AbstractTableModel
    private String[] columnNames = {"name","id","dep","cat","rem","chkout"};
    Object[][] data;
    public MyTableModel()
    try{
    connect conn=new connect();
    ResultSet rs3=conn.rsf("select * from usertab");
    ResultSetMetaData rsmd=rs3.getMetaData();
    int col=rsmd.getColumnCount();
    int cou=0;while(rs3.next()){cou++;}
    data=new Object[cou][col];
    System.out.println(cou+" "+col);
    ResultSet rs2=conn.rsf("select * from usertab");
    int i=0;int j=0;
    for(i=0;i<cou;i++)
    rs2.next();
    for(j=0;j<col;j++)
    data[i][j]=rs2.getString(getColumnName(j));
    System.out.println(data[0][2]);
    }catch(Exception e){System.out.println("DFD "+e);}
            public int getColumnCount() {
                return columnNames.length;
            public int getRowCount() {
                return data.length;
            public String getColumnName(int col) {
                return columnNames[col];
            public Object getValueAt(int row, int col) {
                return data[row][col];
           public Class getColumnClass(int c) {
              return getValueAt(0, c).getClass();
            public boolean isCellEditable(int row, int col) {
                if (col < 2) {
                    return false;
                } else {
                    return true;
            public void setValueAt(Object value, int row, int col) {
                data[row][col] = value;
                fireTableCellUpdated(row, col);
    class MyFrame extends JFrame
    public MyFrame()
         setSize(600,500);
         JPanel p1=new JPanel();
         p1.setBackground(new Color(198,232,189));
         JTable table = new JTable(new MyTableModel());
         table.setPreferredScrollableViewportSize(new Dimension(500,200));
         table.setBackground(new Color(198,232,189));
         JScrollPane scrollPane = new JScrollPane(table);
         scrollPane.setBackground(new Color(198,232,189));
         p1.add(scrollPane);
         getContentPane().add(p1);
    /*Main Class*/
    class test2
         public static void main(String args[])
         MyFrame fr =new MyFrame();
         fr.setVisible(true);
    }thanx

    hi nickelb,
    i had returned Object.class in the getColumnClass() method. But then i
    got NullPointerException at getRowCount() method. i could understand that the
    main problem is in data[][] object. In all the methods its returning null values as it is so declared outside the construtor. But if i declare the object inside the constructor, then the methods could not recognize the object. it seems i cant do the either ways. hope u understood the problem.
    thanx

  • Problem with refreshing jtable. help please urgent.

    hi there
    i can refresh the table now, but the problem is that every time it refreshes, it adds the same data to the freshed table. i just need the table to display what was displayed few seconds ago unless there is change in the datasource. here is my code:
    public void run()
    String selectSQL = "select * from buyerordertable";
    int rowCounter = 1;
    boolean okay = true;
    ResultSet rs;
    Vector rowdata = new Vector();
    Vector columNames = new Vector();
    columNames.add("order Id");
    columNames.add("suplier name");
    columNames.add("item name");
    columNames.add("model");
    columNames.add("quantity");
    columNames.add("price");
    columNames.add("description");
    columNames.add("job Id");
    columNames.add("order confirm Id");
    while (okay)
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:wgclientdatabase", "admin", "");
    PreparedStatement ps = con.prepareStatement(selectSQL);
    rs = null;
    rs = ps.executeQuery();
    while(rs.next())
    Vector temp =new Vector();
    String orderid = rs.getString("OrderID");
    temp.add(orderid);
    String supplier =rs.getString("supplierName");
    temp.add(supplier);
    String item = rs.getString("ItemName");
    temp.add(item);
    String model = rs.getString("Model");
    temp.add(model);
    String quantity = rs.getString("Quantity");
    temp.add(quantity);
    String price = rs.getString("Price");
    temp.add(price);
    String description = rs.getString("Description");
    temp.add(description);
    String jobid = rs.getString("JobID");
    temp.add(jobid);
    String confirmid = rs.getString("OrderConfirmID");
    temp.add(confirmid);
    rowdata.add(temp);
    }catch (SQLException sqle)
    catch(ClassNotFoundException ce)
    try
    /*the table keeps adding old data to the refreshed table. i start with one row of data, after every second, a new row of same data is added to the table. i don't know why.*/
    DefaultTableModel newmodel =(DefaultTableModel)jTable.getModel();
    newmodel.setDataVector(rowdata, columNames);
    jScrollPane.repaint();
    Thread.sleep(1000);
    catch (InterruptedException e)
    okay = false;
    }

    hi there
    thank you for your reply
    doesn't the tablemodel keep one set of data? every time i refresh the table, the table model should only provide same data over and over unless it is reset again? in my program, the result seems like the table model is cumulating data every time it refreshes. and the display is growing with the same data. i already use the
    newmodel.setDataVector(rowdata, columNames);
    to reset the data. ideally the table should only display rowdata. some people say that just using table model will solve the refreshing task. i am not sure if they have my kind of problem.

  • Can anybody help me in fixing the problem ? of JTable ( CODE GIVEN )

    My problem is
    1)when i select the combo box (2nd column) through keyboard the selected item is not visible in the cell
    2) i need to press TAB key twice to go to next cell .
    3) also before editing i need to press a key to start editing (caret visible) HELP ME
    CODE CAN BE RUN TO SEE WHAT I MEANT
    <code>
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Vector;
    import java.text.*;
    public class BaseTable
    public JScrollPane scrollPane;
         public JTable table;
         public int totalRows;
         public int i,numRows,numCols;
         public TableModel model;
         public int rowCount;
         public JComboBox box;
    public BaseTable()
              String[] items=new String[]{"item1","jItem2","kItem3","Item4","Item5","Item6"};
              String[] columns = {"Column1","Column2","Column3","Column4","Column5","Column6","Column7","Column8","Column9"};
              box=new JComboBox(items);
              box.setEditable(true);
    DefaultTableModel baseModel=new DefaultTableModel();
              baseModel.setColumnIdentifiers(columns);
    table = new JTable(baseModel)
                   protected void processKeyEvent(KeyEvent e)
                        if ( e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() != e.VK_TAB)
                             int column = table.getSelectedColumn();
                             int row = table.getSelectedRow();
                             Rectangle r = getCellRect(row, column, false);
                             Point p = new Point( r.x, r.y );
                             SwingUtilities.convertPointToScreen(p, table);
                             try
                                  System.out.println("PROCESS KEY EVENT Typing"+e.getKeyCode());
                                  Robot robot = new Robot();
                                  robot.mouseMove(p.x, p.y );
                                  robot.mousePress(InputEvent.BUTTON1_MASK);
                                  robot.mouseRelease(InputEvent.BUTTON1_MASK);
                                  robot.mouseMove(0, 0 );
                             catch (Exception e2) {}
                        else
                             System.out.println("PROCESS KEY EVENT IN ELSE");
                             if(e.getKeyCode() == e.VK_TAB && table.isEditing())
                                  ((DefaultCellEditor)table.getCellEditor()).stopCellEditing();
                             else
                                  super.processKeyEvent(e);
    Vector vectorRow = new Vector();
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              TableCellEditor tableCellEditor_comboBox = new MyCustomTableCellEditor(box,this);
              table.getColumnModel().getColumn(1).setCellEditor(tableCellEditor_comboBox);
              ((DefaultTableModel)table.getModel()).addRow(vectorRow);
              rowCount = table.getRowCount();
              ((DefaultTableModel)table.getModel()).fireTableRowsInserted(rowCount,rowCount);
              scrollPane = new JScrollPane(table);
              scrollPane.setForeground(Color.white);
              rowCount = table.getRowCount();
    numCols = table.getColumnCount();
    public class MyCustomTableCellEditor extends DefaultCellEditor
                   JTable table=null;
                   BaseTable baseTable=null;
                   JComboBox box=null;
                   MyCustomTableCellEditor(JComboBox editorComponent,BaseTable baseTable)
                        super(editorComponent);
                        this.table=baseTable.table;
                        this.baseTable=baseTable;
                        setClickCountToStart(0);
                   public Component getTableCellEditorComponent(
                        JTable table,
                        Object value,
                        boolean isSelected,
                        int row,
                        int column)
                             super.getTableCellEditorComponent(table,value,isSelected,row,column);
                             box=(JComboBox)getComponent();
                             box.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
                             return box;
         public static void main(String s1[])
              BaseTable t=new BaseTable();
              JFrame f=new JFrame();
              f.getContentPane().add(t.scrollPane);
              f.setSize(800,200);
              f.setVisible(true);
    </code>

    sahas@sun, you're very impolite! farukkhan was trying to help, and he's right because when you use code formatting the code is really easier to read.
    Perhaps you have lost a chance for getting the answer!

  • Problem in Printing jtable swing component using dot martix Epson printer

    Hello,
         I am devoloping desktop aplication using swing.In which i want to prit jtable on paper using dot matrix printer.
    It works well if i am not chnging the font.But if i changed the font (to my local language or any any other language)
    the printing text in table gets Blur (Characters in the text get ovewrites to each other and it become hard to recognize).
    Please help me in this problem.I am trying this from more than two days but not yet found the solution.
    Thank you,
    Dattatray

    Joerg22 wrote:
    Windows allows to change the keyboard to Hindi, but not to Marathi.
    But I wonder why you are changing the focus. The problem arose when you were setting a particular font. So the first question is: Can you do without that font? Meaning: are the Devanagari characters an option?No Devanagari characters are not option.I have to use Marathi language in my application for displaying to the user and taking value from user.See perblem come into picture when i am using setFont method.i did one expriment using characters 0900-097F.For one jtext field i have set text as "\u0937\u0937\0937".In gui i saw the corresponding marathi characters for it (here i did not used any set font method).Also after printuing that on paper i saw marathi text.As i mentioned in previous post i was not able to use "\u0937\u0937\0937" this in table.It might be some mistake in string formation.But i am sure it will work.Only need to check how to form string.
    In this case Only problem is that how to take input from user.As user will not gonna input "\u0900".He will laways enter abcd....I have to interprete them into unicode.Please correct me if i am thinking wrong.
    I will try by changing the language of keyboard to hindi and get back.
    Edited by: Ashtekar on Aug 9, 2010 2:13 AM
    Edited by: Ashtekar on Aug 9, 2010 2:13 AM

  • Problem in editing JTable fields.....

    Hi there!!
    I have got 2 classes in my package,one contains a public static JTable while the other has got some variables whose values I want the JTable's fields to populate with.Now the problem I have is that I can't populate the JTable's fields after making it's class's object and accessing the JTable using that object...Can anybody help plz?
    Thanks...

    Hi Cantry!!
    I'm embedding my code in this post,,had to simplify the code as my application's code may not have been understandable,,,
    Here's the code
    //THIS IS THE CLASS CONTAINING JTable
    import java.sql.*;
    import java.util.StringTokenizer;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;
    import javax.swing.*;
    public class Test_GUI extends javax.swing.JFrame {
        /** Creates new form Test_GUI */
        public Test_GUI() {
            initComponents();
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                     
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("New Allocations");
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane1.setViewportView(jTable1);
            org.jdesktop.layout.GroupLayout layout = new
    org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(57, 57, 57)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 344,
    org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(106, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(55, 55, 55)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 143,
    org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(247, Short.MAX_VALUE))
            pack();
        }// </editor-fold>                       
         * @param args the command line arguments
        public static void main(String args[]) {
            Test_GUI tg2=new Test_GUI();
            tg2.SetTableValues();
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Test_GUI().setVisible(true);
            try
    javax.swing.UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    catch(Exception e)
                        e.printStackTrace();
            Test_GUI tg=new Test_GUI();
            tg.setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JScrollPane jScrollPane1;
        public static javax.swing.JTable jTable1;
        // End of variables declaration                  
        private javax.swing.JTextField jTextField6;
        public static void SetTableValues()
            System.out.println("here");
            Data_Class dc=new Data_Class();
            jTable1.setValueAt(dc.Test_data,0,0);
    and code from the other calss,,,
    //CLASS FROM WHERE I'M FETCHING THE DATA
    public class Data_Class {
        static String Test_data="testdata";
        /** Creates a new instance of Data_Class */
        public Data_Class() {
    }thanks in advance...

  • Date Format problem in a JTable, help plzzz !!!

    Hi,
    i have a JTable which contains multiple date columns, and more particulary, Timestamp columns.
    I mean this format : yyyy-mm-dd hh:mm:ss.fffffffff
    I only need hh:mm:ss informations for my JTable.
    The problem is when i retrieve the datas in the JTable (which has a bean Select for model), the date column has this format : yyyy-mm-dd (only the date), and the time is not present !
    What must i do to have only a part of the timestamp data in the column ??
    Thanks in advance
    Steve

    If you want to format data in any way other than the default in a JTable, you need a table cell renderer. Sun's tutorial on how to use JTables explains them.

  • Problems with JList & JTable in Netbeans 5.5

    Hi,
    Netbeans provides good GUI building provider.
    But when i am adding JList inside panel
    and trying to add elements its giving error.
    So how to modify read only code in netBeans 5.5 generated code. ??
    There is problem accessing JList variable to be modify.
    HOW TO ACHIEVE THIS ????
    because When you add JList in your GUI Part.
    Netbeans generates code automatically.
    we can't change it.
    HOW TO DO it... ???

    I have had similar trouble.
    In NetBeans Guieditor, JList and JTable are automatically created in a JScrollPanel. This is good as it saves you lots of formatting.
    PROBLEM: when you click/select the JTable or JList in the GUI Editor the Properties box (right hand side ) only shows properties for the JScrollPane.
    So you will only be able to edit Init code etc for the JScrollPane
    SOLUTION: The "Members View" is a list of members (Panels, Objects, etc) on the left hand side of the screen.
    The JScrollPane is listed there. You simply click on this to expand and select the JTable/JList that it contains.
    When you select the JTable/JList the Properites window (right side of screen) now shows the properties for the component you really want to deal with.
    The code options are very powerful.

  • Need help with inserting rows in ResultSet and JTable

    hello Guru!
    i have inserted a row in my result set and i want that my table shows this row promptly after i have inserted it in my result set...
    but when i use following code for my resultset:
    rs.moveToInsertRow();
    rs.updateInt(1,nr);
    rs.updateString(2, name);
    rs.insertRow();
    Record are inserted in resultset and database but not shown in my JTable??
    Anyone a Clue to without reexecuting the query how can i display inserted row in JTable
    http://download-west.oracle.com/docs/cd/A87860_01/doc/java.817/a83724/resltse7.h
    I have refrered the following links but still clue less help Guruuuuuuu
    i m really in trobble??????

    i am just near by the Solution using the Database Metadata
    by couldn't get the ideaaaa
    ==================================================
    http://download-west.oracle.com/docs/cd/A87860_01/doc/java.817/a83724/resltse7.htm
    Seeing Database Changes Made Internally and Externally
    This section discusses the ability of a result set to see the following:
    its own changes (DELETE, UPDATE, or INSERT operations within the result set), referred to as internal changes
    changes made from elsewhere (either from your own transaction outside the result set, or from other committed transactions), referred to as external changes
    Near the end of the section is a summary table.
    Note:
    External changes are referred to as "other's changes" in the Sun Microsystems JDBC 2.0 specification.
    Seeing Internal Changes
    The ability of an updatable result set to see its own changes depends on both the result set type and the kind of change (UPDATE, DELETE, or INSERT). This is discussed at various points throughout the "Updating Result Sets" section beginning on , and is summarized as follows:
    Internal DELETE operations are visible for scrollable result sets (scroll-sensitive or scroll-insensitive), but are not visible for forward-only result sets.
    After you delete a row in a scrollable result set, the preceding row becomes the new current row, and subsequent row numbers are updated accordingly.
    Internal UPDATE operations are always visible, regardless of the result set type (forward-only, scroll-sensitive, or scroll-insensitive).
    Internal INSERT operations are never visible, regardless of the result set type (neither forward-only, scroll-sensitive, nor scroll-insensitive).
    An internal change being "visible" essentially means that a subsequent getXXX() call will see the data changed by a preceding updateXXX() call on the same data item.
    JDBC 2.0 DatabaseMetaData objects include the following methods to verify this. Each takes a result set type as input (ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_SENSITIVE, or ResultSet.TYPE_SCROLL_INSENSITIVE).
    boolean ownDeletesAreVisible(int) throws SQLException
    boolean ownUpdatesAreVisible(int) throws SQLException
    boolean ownInsertsAreVisible(int) throws SQLException
    Note:
    When you make an internal change that causes a trigger to execute, the trigger changes are effectively external changes. However, if the trigger affects data in the row you are updating, you will see those changes for any scrollable/updatable result set, because an implicit row refetch occurs after the update.
    Seeing External Changes
    Only a scroll-sensitive result set can see external changes to the underlying database, and it can only see the changes from external UPDATE operations. Changes from external DELETE or INSERT operations are never visible.
    Note:
    Any discussion of seeing changes from outside the enclosing transaction presumes the transaction itself has an isolation level setting that allows the changes to be visible.
    For implementation details of scroll-sensitive result sets, including exactly how and how soon external updates become visible, see "Oracle Implementation of Scroll-Sensitive Result Sets".
    JDBC 2.0 DatabaseMetaData objects include the following methods to verify this. Each takes a result set type as input (ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_SENSITIVE, or ResultSet.TYPE_SCROLL_INSENSITIVE).
    boolean othersDeletesAreVisible(int) throws SQLException
    boolean othersUpdatesAreVisible(int) throws SQLException
    boolean othersInsertsAreVisible(int) throws SQLException
    Note:
    Explicit use of the refreshRow() method, described in "Refetching Rows", is distinct from this discussion of visibility. For example, even though external updates are "invisible" to a scroll-insensitive result set, you can explicitly refetch rows in a scroll-insensitive/updatable result set and retrieve external changes that have been made. "Visibility" refers only to the fact that the scroll-insensitive/updatable result set would not see such changes automatically and implicitly.
    Visibility versus Detection of External Changes
    Regarding changes made to the underlying database by external sources, there are two similar but distinct concepts with respect to visibility of the changes from your local result set:
    visibility of changes
    detection of changes
    A change being "visible" means that when you look at a row in the result set, you can see new data values from changes made by external sources to the corresponding row in the database.
    A change being "detected", however, means that the result set is aware that this is a new value since the result set was first populated.
    With Oracle8i release 8.1.6 and higher, even when an Oracle result set sees new data (as with an external UPDATE in a scroll-sensitive result set), it has no awareness that this data has changed since the result set was populated. Such changes are not "detected".
    JDBC 2.0 DatabaseMetaData objects include the following methods to verify this. Each takes a result set type as input (ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_SENSITIVE, or ResultSet.TYPE_SCROLL_INSENSITIVE).
    boolean deletesAreDetected(int) throws SQLException
    boolean updatesAreDetected(int) throws SQLException
    boolean insertsAreDetected(int) throws SQLException
    It follows, then, that result set methods specified by JDBC 2.0 to detect changes--rowDeleted(), rowUpdated(), and rowInserted()--will always return false with the 8.1.6 Oracle JDBC drivers. There is no use in calling them.
    Summary of Visibility of Internal and External Changes
    Table 12-1 summarizes the discussion in the preceding sections regarding whether a result set object in the Oracle JDBC implementation can see changes made internally through the result set itself, and changes made externally to the underlying database from elsewhere in your transaction or from other committed transactions.
    Table 12-1 Visibility of Internal and External Changes for Oracle JDBC
    Result Set Type Can See Internal DELETE? Can See Internal UPDATE? Can See Internal INSERT? Can See External DELETE? Can See External UPDATE? Can See External INSERT?
    forward-only
    no
    yes
    no
    no
    no
    no
    scroll-sensitive
    yes
    yes
    no
    no
    yes
    no
    scroll-insensitive
    yes
    yes
    no
    no
    no
    no
    For implementation details of scroll-sensitive result sets, including exactly how and how soon external updates become visible, see "Oracle Implementation of Scroll-Sensitive Result Sets".
    Notes:
    Remember that explicit use of the refreshRow() method, described in "Refetching Rows", is distinct from the concept of "visibility" of external changes. This is discussed in "Seeing External Changes".
    Remember that even when external changes are "visible", as with UPDATE operations underlying a scroll-sensitive result set, they are not "detected". The result set rowDeleted(), rowUpdated(), and rowInserted() methods always return false. This is further discussed in "Visibility versus Detection of External Changes".
    Oracle Implementation of Scroll-Sensitive Result Sets
    The Oracle implementation of scroll-sensitive result sets involves the concept of a window, with a window size that is based on the fetch size. The window size affects how often rows are updated in the result set.
    Once you establish a current row by moving to a specified row (as described in "Positioning in a Scrollable Result Set"), the window consists of the N rows in the result set starting with that row, where N is the fetch size being used by the result set (see "Fetch Size"). Note that there is no current row, and therefore no window, when a result set is first created. The default position is before the first row, which is not a valid current row.
    As you move from row to row, the window remains unchanged as long as the current row stays within that window. However, once you move to a new current row outside the window, you redefine the window to be the N rows starting with the new current row.
    Whenever the window is redefined, the N rows in the database corresponding to the rows in the new window are automatically refetched through an implicit call to the refreshRow() method (described in "Refetching Rows"), thereby updating the data throughout the new window.
    So external updates are not instantaneously visible in a scroll-sensitive result set; they are only visible after the automatic refetches just described.
    For a sample application that demonstrates the functionality of a scroll-sensitive result set, see "Scroll-Sensitive Result Set--ResultSet5.java".
    Note:
    Because this kind of refetching is not a highly efficient or optimized methodology, there are significant performance concerns. Consider carefully before using scroll-sensitive result sets as currently implemented. There is also a significant tradeoff between sensitivity and performance. The most sensitive result set is one with a fetch size of 1, which would result in the new current row being refetched every time you move between rows. However, this would have a significant impact on the performance of your application.
    how can i implement this using
    JDBC 2.0 DatabaseMetaData objects include the following methods to verify this. Each takes a result set type as input (ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_SENSITIVE, or ResultSet.TYPE_SCROLL_INSENSITIVE).
    boolean deletesAreDetected(int) throws SQLException
    boolean updatesAreDetected(int) throws SQLException
    boolean insertsAreDetected(int) throws SQLException

  • Problem displaying table (JTABLE), can u help me?

    Hi 2 all.
    I'm beginer in java (I have expirience of some yoears developing in pro-C, but not java).
    I try to create some JDialog using Intellig Idea7. There I create JTable component, try to initialize it with values in the array (that was inialized before)
    (ex:
    JTable table1 = new JTable(data_string_array, row_names_array);
    The problem is when I try to make & run application, there is nothing displayed.
    On "debug prints" ( print(table1.getValueAt(0,0)); ) where I try to print values of the table - everything is right. it print right values, but then aren't displayed on the dialog window.
    What could be a problem?
    here is example of the code:
    import javax.swing.*;
    import java.awt.event.*;
    * Created by IntelliJ IDEA.
    * User: db2admin
    * Date: Jul 10, 2008
    * Time: 11:53:43 AM
    * To change this template use File | Settings | File Templates.
    public class frame1 extends JFrame{
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTable table1;
    private JScrollPane scrollpane;
    public frame1 ()
    contentPane = new JPanel();
    setContentPane(contentPane);
    getRootPane().setDefaultButton(buttonOK);
    // Create table data:
    Object[][] data_matrix = {
    {"one", "two"},
    {"five", "six"},
    {"nine", "ten"},
    Object[] row_names = {"1row1", "2row2"};
    // create new table instance
    table1 = new JTable(data_matrix, row_names);
    scrollpane = new JScrollPane(table1);
    System.out.println("this print");
    buttonOK.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    onOK();
    buttonCancel.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    onCancel();
    // call onCancel() when cross is clicked
    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    onCancel();
    // call onCancel() on ESCAPE
    contentPane.registerKeyboardAction(new ActionListener()
    public void actionPerformed(ActionEvent e)
    onCancel();
    }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    private void onOK()
    // add your code here
    //dispose();
    private void onCancel()
    // add your code here if necessary
    dispose();
    public static void main(String[] args)
    frame1 dialog = new frame1();
    dialog.pack();
    dialog.setVisible(true);
    System.out.println("This is other print");
    //JTableDemo demo = new JTableDemo();
    //System.exit(0);
    P.S. Other question: what principal difference in creating simple forms as JFrame or JDialog?

    Hi!
    Well, I don't know what IntellyJ makes, but
    1) I can't see where the buttons are created, so addActionListener throws NPE.
    2) I can't see where the scrollPane is added to the contentPane
    Andras_

  • Problem  Search Records JTable

    Hello All,
    I'm newbie in java, somebody help me..,i've problem using JTable.I have 6 Column in one JTable and i'm using MS Access database,example :
    i want to search records in JTable , i press keyboard and first cell Focus,then i typed ID records result into JTable column1,column2, and column3,column4 i'm entry agains,entry the student point and the last column summary from column 3 and column 3 value1 + value 2 / 2 , and i want to search Smith Data for the example :
    1.
    ==============================================
    ID Name Address value1 value2 total
    ==============================================
    123 ..... ....... .... ..... ......
    ==============================================
    2.
    ==============================================
    ID Name Address value1 value2 total
    ==============================================
    123 Smith St Louis ... ..... ......
    ==============================================
    3.
    ==============================================
    ID Name Address value1 value2 total
    ==============================================
    123 Smith St Louis 70 70 ......
    ==============================================
    4.
    ==============================================
    ID Name Address value1 value2 total
    ==============================================
    123 Smith St Louis 70 70 70
    ==============================================

    The Java&#8482; Tutorials: [How to Use Tables|http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]
    db

  • Problem while reading JTable from JTextPane

    Hi,
    I am facing a bizarre problem. My JTextPane can contain rich text, image and table. While I am reading the tables from the JTextPane, I find that if there are more than one JTable, then the second table is returned first, then the first table.
    Still I have not found the exact pattern it returns when there are more than one table in the JTextPane, however I am getting the table in a different sequence than they were entered in the TextPane.
    Thanks in advance for the help.

    Hi,
    I am facing a bizarre problem. My JTextPane can contain rich text, image and table. While I am reading the tables from the JTextPane, I find that if there are more than one JTable, then the second table is returned first, then the first table.
    Still I have not found the exact pattern it returns when there are more than one table in the JTextPane, however I am getting the table in a different sequence than they were entered in the TextPane.
    Thanks in advance for the help.

Maybe you are looking for