AbstractTableModelS

I'm new to java so please forgive any confusion with terminology etc, I'm currently sourcing a good reference text to use.
Basically I've got an AbstractTableModel class (MyTableModel) that creates a table model. To create the table model its constructor is fed a resultset (and table name not currently needed for my purposes) from another class thus
public MyTableMode aTblModel;
aTblModel = new MyTableModel(rsResultSet,"TableName");
Everything works OK so far with one table.
What I'm trying to do is to use this same AbstractModelClass (why write more code) to provide table models for more than one table (the ui allows the user to have concurrent access to multiple tables). Something like
aTblModel = new MyTableModel(rsResultSetA,"TableNameA") ;
bTblModel = new MyTableModel(rsResultSetB,"TableNameB") ;
However I'm obviously missing something major cause both instance variables wind up holding info for rsResultSetB (or whichever is called last) . I've tried various ways of setting the instance variables most work for one table but none establish two separate table models. I'm starting to wonder if I need to put each table model (aTblModel,bTblModel) into a vector or an array or something to differentiate them.
Any help is much appreciated, a nudge in the right direction at this point will save me much time - thanks.

I think the tablemodel is working for a single table but not when I put a second result set through it.
According to an article in the JDJ the AbstractTableModel has additional functionality so thats why I went down that path.
Here is some code that should be an example of the problem. Because the problem involves resultsets being fed to the tablemodel class I've included connection to a Access db (dummy.mdb) which just needs to be an empty mdb file - you'll see by the url. Two tables are created with two result sets and, unsuccessfully, two tablemodels. There are two classes for the example: UI the main class and TM the table model class. I've been using NetBeans to run this and everything ran OK to show the problem
Thanks again
--------------------------UI--------------------------------------
// UI
package ATMTest;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;
import java.lang.*;
import java.sql.*;
import ATMTest.TM.*;
//Declare a class
// table model is in the TM class
public class UI
// CONSTRUCTOR
public UI() {
try{
//-------Create dummy result sets
//NEEDS an empty mdb file dummy.mdb on root of c
UI.getConnection();
//MUST HAVE TWO SEPARATE STATEMENT VARS or the first recordset closes when the second is set - strange but true
tblSQLA = dummyCon.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
tblSQLB = dummyCon.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
//CREATE TWO TABLES AND PUT A SOME ROWS IN THEM - TableA and TableB must not be there when running
// ------TABLE A 2 columns 2 rows
tblSQLA.executeUpdate("SELECT 1 AS A1, 2 AS A2 INTO TableA;");
tblSQLA.executeUpdate("INSERT INTO TableA ( A1, A2 ) SELECT 2 AS Expr1, 3 AS Expr2;");
rsA = tblSQLA.executeQuery("SELECT * FROM TableA;");
//Instantiate the tblModel variable
tblModelA = new TM(rsA,"TableA") ;
//******TEST Table A should be A1
JOptionPane.showMessageDialog(null,"Table A 1st col = " + tblModelA.getColumnName(0), null, JOptionPane.INFORMATION_MESSAGE);
//--------TABLE B 3 columns 3 rows
tblSQLB.executeUpdate("SELECT 5 AS B1, 6 AS B2 ,99 as B3 INTO TableB;");
tblSQLB.executeUpdate("INSERT INTO TableB ( B1, B2, B3 ) SELECT 6 AS Expr1, 7 AS Expr2, 100 as Expr3;");
tblSQLB.executeUpdate("INSERT INTO TableB ( B1, B2, B3 ) SELECT 8 AS Expr1, 9 AS Expr2, 101 as Expr3;");
rsB = tblSQLB.executeQuery("SELECT * From TableB;");
tblModelB = new TM(rsB,"TableB") ;
//******TEST Table B should be B1
JOptionPane.showMessageDialog(null,"Table B 1st col = " + tblModelB.getColumnName(0), null, JOptionPane.INFORMATION_MESSAGE);
//******TEST Try model A again this should be A1 --- BUT ITS B1
JOptionPane.showMessageDialog(null,"Table A (after TableB model) 1st col = " + tblModelA.getColumnName(0), null, JOptionPane.INFORMATION_MESSAGE);
catch(SQLException e)
{System.out.println("boo" + e.getMessage());
catch (Exception e)
{   // Catch a connection failure
e.printStackTrace(System.err);
JOptionPane.showMessageDialog(null,"Connected to db failed: General Failure",
null,JOptionPane.INFORMATION_MESSAGE);
//Close the resultsets and connection
try{
rsA.close();
rsB.close();
dummyCon.close();
catch(SQLException e)
{System.out.println("hoo" + e.getMessage());
//Quit the app
System.exit(0);
// Method to Connect to mdb database
public static Connection getConnection()
throws ClassNotFoundException, SQLException
//Vars for the connection
String DBDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(DBDriver);
String DBUrl = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:/dummy.mdb";
String username = "admin";
String password = "";
//Connect and return the connection
return dummyCon = DriverManager.getConnection(DBUrl, username, password);
// MAIN METHOD
public static void main(String[] args)
UI uiMain = new UI();
     } // Closes main method
//Vars
public static ResultSet rsA, rsB ;
private Statement tblSQLA, tblSQLB ;
public static TM tblModelA, tblModelB;
private static Connection dummyCon;
} // CLOSE UI class
--------------------------TM--------------------------------------
// This is the tables model
package ATMTest;
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.Vector;
public class TM extends AbstractTableModel {
ResultSetMetaData rsMetaData;
     Vector allRows; // Contains all rows of the result set
     Vector row; // Individual row for a result set
     Vector colNames; // Contains all column names of the result set
     public static String dbColNames[];
     String pkValues[];
     String pKeyCol;
     Vector deletedKeys;
Vector newRow;
     Vector newRows;
     boolean ibRowNew = false;
     boolean ibRowInserted = false;
// Constructor
public TM(ResultSet rsIn, String tblNameIn){
this.rsTM = rsIn;
this.reqTblName = tblNameIn;
try{              
deletedKeys = new Vector();
          newRows = new Vector();
          ResultSetMetaData rsMetaData = rsTM.getMetaData();
colNum = 0;
rowNum = 0;
//GET THE num of cols and then go over them and get their names
          colNum = rsMetaData.getColumnCount();
          dbColNames = new String[colNum];
     for(int col = 0; col < colNum; col ++){
               dbColNames[col] = rsMetaData.getColumnName(col + 1);
          allRows = new Vector();
          while(rsTM.next()){
newRow = new Vector();
for(int i = 1; i <= colNum; i++){
     newRow.addElement(rsTM.getObject(i));
} // for
allRows.addElement(newRow);
//rowNum++;
          } // while
rowNum = getRowCount();
JOptionPane.showMessageDialog(null,"TableModel execution: " + reqTblName + " col# " + colNum + " row# " + rowNum, null, JOptionPane.INFORMATION_MESSAGE);
System.out.println ("TableModel execution: " + reqTblName + " col# " + colNum + " row# " + rowNum);
     catch(SQLException e){
          System.out.println(e.getMessage());
}//End of TM CONSTRUCTOR
public String getColumnName(int col){
     return dbColNames[col];
public int getRowCount(){
     return allRows.size();
public int getColumnCount(){
     return colNum;
public Object getValueAt(int arow, int col){
     row = (Vector) allRows.elementAt(arow);
     return row.elementAt(col);
//Var declaration
private static ResultSet rsTM ;
private static String reqTblName;
private Statement sqlStatement;
public static int colNum ;
public static int rowNum ;
} // END CLASS

Similar Messages

  • Adding Rows Dynamically using AbstractTableModel

    I would do anything for some help on this one. I have a JTable that has 5 rows within 1 column. After the user gets to the 5th row I want them another row to be added so that they could add informatoin in there. When I do this with the following code below nothing happens and my column count ends up being -1 right after I do this. If anyone could help it this would be a great help. The output in my console when I end up putting information into all the rows up to the 4th one is the following.
    Vector size 0
    column count1
    column count1
    row 0column 0
    row 1column 0
    row 2column 0
    row 3column 0
    row 4column 0
    column count1
    row 4column -1
    /*********This is my AbstractTableModel Class *********/
    package com.ibm.esup.agent.dataqmonitor;
    * @author garbersb
    * This class sets up the Table Model for the Message Input Queue.
    import java.util.*;
    import javax.swing.table.*;
    import javax.swing.*;
    public class QueueTableModel extends DefaultTableModel
         /** Vector where the message information will be kept. */
         Vector data = null;
         /** Number of columns within the input queue table. */
         protected static int NUM_COLUMNS = 1;
         /** Number of rows within the input queue table. */
         protected static int START_NUM_ROWS = 5;
         /** Next row that could be empty. */
         protected int nextEmptyRow = 0;
         /** Number of rows we are at. */
         protected int numRows = 0;
         * @see java.lang.Object#Object()
         * This will end up creating a Vector when this gets created.
         public QueueTableModel()
              data = new Vector();
              System.out.println("Vector size " + data.size());
         * @see javax.swing.table.TableModel#getColumnName(int)
         * This will allow us to get the Column Name.
         public String getColumnName(int column)
              switch (column)
              return "";
         * @see javax.swing.table.TableModel#getColumnCount()
         public synchronized int getColumnCount()
              System.out.println("column count" + NUM_COLUMNS);
              return NUM_COLUMNS;
         * @see javax.swing.table.TableModel#getRowCount()
         public synchronized int getRowCount()
              if (numRows < START_NUM_ROWS)
                   return START_NUM_ROWS;
              else
                   return numRows;
         * @see javax.swing.table.TableModel#getValueAt(int, int)
         public synchronized Object getValueAt(int row, int column)
              try
                   String queue = (String) data.elementAt(row);
                   switch (column)
                        case 0 :
                             return queue;
              catch (Exception e)
              return "";
         * Don't need to implement this method unless your table's
         * editable.
         public boolean isCellEditable(int row, int col)
              return true;
         * Don't need to implement this method unless your table's
         * data can change.
         public void setValueAt(Object value, int row, int col)
              String queueValue = (String) value;
              data.addElement(queueValue);
              fireTableCellUpdated(row, col);
         * * inserts a row at the end of the table model */
         /*public void insertRow(){      
              int length = getRowCount();
              for (int i=0; i<length ; i++)
              //just add blank string values in this instance but your
              //code will initialise a default object no doubt
              data.addElement("");
              //baseData is the vector containing all your row vectors
              fireTableDataChanged();
         public void addRow()
              addRow(data);
              fireTableDataChanged();
         * Method updateQueue.
         * This method will allow us to update the queues with the latest
         * and greatest information of what messages got added or are
         * on the queue and what time the messages occurred.
         * @param monitorMsgObject
         public synchronized void updateQueue(MonitorMessageObject monitorMsgObject)
         public static void main(String[] args)
    /*********** THis is my main gui class that will has a TableListener and ActionHandler inner - classes within *************/
    package com.ibm.esup.agent.dataqmonitor;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.IOException;
    import java.util.Vector;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPasswordField;
    import javax.swing.JTextField;
    import javax.swing.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableModel;
    import com.ibm.as400.access.AS400;
    import com.ibm.as400.access.AS400Exception;
    import com.ibm.as400.access.AS400SecurityException;
    * @author garbersb *
    * This will allow the user to sign onto a particular system
    * with a valid user id and password.
    public class SignOn extends JFrame
         /** Label for the system name. */
         private JLabel labelSystemName;
         /** Label for the user name. */
         private JLabel labelUserName;
         /** Label for the password. */
         private JLabel labelPassword;
         /** Label for input queue. */
         private JLabel labelInputQueue;
         /** Label for output queue. */
         private JLabel labelOutputQueue;
         /** Text Field for the system name. */
         private JTextField textFieldSystemName;
         /** Text Field for the user name. */
         private JTextField textFieldUserName;
         /** Text Field for the password. */
         private JPasswordField textFieldPassword;
         /** Text Field for the input queue. */
         private JTextField textFieldInputQueue;
         /** Text Field for the output queue. */
         private JTextField textFieldOutputQueue;
         /** Button that will allow the user to submit. */
         private JButton buttonSubmit;
         /** String that will be used for the system name,
         * user name and password. */
         private String systemName, userName, password, inputQueue, outputQueue;
         /** Label for the input table where different queues
         * can be entered. */
         private JLabel labelQueueInput = null;
         /** One Column table where users can enter different
         * queues that they want to view. */
         private JTable tableQueueInput = null;
         /** Scroll pane that will be used to put the
         * table inside of it. */
         private JScrollPane scrollPaneQueueInput = null;
         /** Label for the interval time that they want to
         * check these different queues. */
         private JLabel labelIntervalCheck = null;
         /** Table panel */
         private JPanel panelTable = null;
         /** Text Field where users can enter a number
         * that will end up being the time that this application
         * will check thes queues. (This is in milli-seconds)
         * For example if a user wants to check the queue every 5 minutes
         * they would enter 60000 within this text field. */
         private JTextField textFieldIntveralCheck = null;
         /** Table Model Input Queue */
         private QueueTableModel tableModelInputQueue = null;
         /** AS400 system object that will be used to sign
         * onto an iSeries system. */
         private AS400 system;
         * Method loadGui.
         * This will load the Sign On Frame and will allow the
         * user to enter the information within the Text Field
         * or specify an xml file that has TCP information already
         * in it.
         public void loadGui()
              //Set the Title
              this.setTitle("Sign On to iSeries System");
              Container contentPane = this.getContentPane();
              GridBagLayout gbl = new GridBagLayout();
              GridBagConstraints gbc = new GridBagConstraints();
              gbc.insets = new Insets(10, 10, 10, 10);
              gbc.fill = GridBagConstraints.EAST;
              contentPane.setLayout(gbl);
              labelSystemName = new JLabel("System Name");
              gbc.gridx = 0;
              gbc.gridy = 1;
              gbl.setConstraints(labelSystemName, gbc);
              contentPane.add(labelSystemName);
              textFieldSystemName = new JTextField();
              textFieldSystemName.setColumns(20);
              gbc.gridx = 1;
              gbc.gridy = 1;
              gbc.gridwidth = 4;
              gbl.setConstraints(textFieldSystemName, gbc);
              contentPane.add(textFieldSystemName);
              labelUserName = new JLabel("User Name");
              gbc.gridx = 0;
              gbc.gridy = 2;
              gbl.setConstraints(labelUserName, gbc);
              contentPane.add(labelUserName);
              textFieldUserName = new JTextField();
              textFieldUserName.setColumns(20);
              gbc.gridx = 1;
              gbc.gridy = 2;
              gbc.gridwidth = 4;
              gbl.setConstraints(textFieldUserName, gbc);
              contentPane.add(textFieldUserName);
              labelPassword = new JLabel("Password");
              gbc.gridx = 0;
              gbc.gridy = 3;
              gbl.setConstraints(labelPassword, gbc);
              contentPane.add(labelPassword);
              textFieldPassword = new JPasswordField();
              textFieldPassword.setColumns(20);
              gbc.gridx = 1;
              gbc.gridy = 3;
              gbc.gridwidth = 4;
              gbl.setConstraints(textFieldPassword, gbc);
              contentPane.add(textFieldPassword);
    /*          labelInputQueue = new JLabel("Interval Check");
              gbc.gridx = 0;
              gbc.gridy = 4;
              gbl.setConstraints(labelInputQueue, gbc);
              contentPane.add(labelInputQueue);
              textFieldInputQueue = new JTextField();
              textFieldInputQueue.setColumns(20);
              gbc.gridx = 1;
              gbc.gridy = 4;
              gbc.gridwidth = 4;
              gbl.setConstraints(textFieldInputQueue, gbc);
              contentPane.add(textFieldInputQueue);
              labelInputQueue = new JLabel("Input Queue");
              gbc.gridx = 0;
              gbc.gridy = 4;
              gbl.setConstraints(labelInputQueue, gbc);
              contentPane.add(labelInputQueue);
              textFieldInputQueue = new JTextField();
              textFieldInputQueue.setColumns(20);
              gbc.gridx = 1;
              gbc.gridy = 4;
              gbc.gridwidth = 4;
              gbl.setConstraints(textFieldInputQueue, gbc);
              contentPane.add(textFieldInputQueue);
              labelOutputQueue = new JLabel("Output Queue");
              gbc.gridx = 0;
              gbc.gridy = 5;
              gbl.setConstraints(labelOutputQueue, gbc);
              contentPane.add(labelOutputQueue);
              textFieldOutputQueue = new JTextField();
              textFieldOutputQueue.setColumns(20);
              gbc.gridx = 1;
              gbc.gridy = 5;
              gbc.gridwidth = 4;
              gbl.setConstraints(textFieldOutputQueue, gbc);
              contentPane.add(textFieldOutputQueue);
              labelQueueInput = new JLabel("Input Queues");
              gbc.gridx = 0;
              gbc.gridy = 6;
              gbl.setConstraints(labelQueueInput, gbc);
              contentPane.add(labelQueueInput);
              tableQueueInput= new JTable();
              scrollPaneQueueInput = new JScrollPane(tableQueueInput);
              Dimension tableQueueInputDimension = new Dimension(220, 100);
              scrollPaneQueueInput.setPreferredSize(tableQueueInputDimension);
              gbc.gridx = 1;
              gbc.gridy = 6;
              gbc.gridwidth = 4;
              gbl.setConstraints(scrollPaneQueueInput, gbc);
              contentPane.add(scrollPaneQueueInput);
              //Setting up the table model input queue.
              tableModelInputQueue = new QueueTableModel();
              tableQueueInput.setModel(tableModelInputQueue);
              TableListener tableListener = new TableListener();
              tableModelInputQueue.addTableModelListener(tableListener);          
              buttonSubmit = new JButton("Submit");
              gbc.gridx = 0;
              gbc.gridy = 7;
              gbl.setConstraints(buttonSubmit, gbc);
              contentPane.add(buttonSubmit);
              RunHandler handler = new RunHandler();
              buttonSubmit.addActionListener(handler);
              //For now we will set the text in the
              //input and output queue for the Analyzer
              //Agent.
              textFieldInputQueue.setText("/qsys.lib/qesp.lib/anz_input.dtaq");
              textFieldOutputQueue.setText("/qsys.lib/qesp.lib/anz_output.dtaq");
         private class TableListener implements TableModelListener {
    public TableListener() {
    public void tableChanged(TableModelEvent e) {
    int row = e.getFirstRow();
    int column = e.getColumn();
    String columnName = tableModelInputQueue.getColumnName(column);
    Object data = tableModelInputQueue.getValueAt(row, column);
    System.out.println("row " + row + "column " + column);
    if (row == 4) {
         tableModelInputQueue.addRow();
              * @author garbersb
              * This will end up creating the System object
         * by getting the system name, user id and
         * password from the Text Field values.
         private class RunHandler implements ActionListener
              * @see java.awt.event.ActionListener#actionPerformed(ActionEvent)
              * When the submit button is selected it will cause the
              * action event to do something.
              public void actionPerformed(ActionEvent e)
                   if (e.getSource() == buttonSubmit)
                        //here we will get the system name, user name
                        //and password.
                        systemName = textFieldSystemName.getText().trim();
                        userName = textFieldUserName.getText().trim();
                        char[] passwordCharArray = textFieldPassword.getPassword();
                        String password = new String(passwordCharArray);
                        inputQueue = textFieldInputQueue.getText().trim();
                        outputQueue = textFieldOutputQueue.getText().trim();
                        //here we will create an AS400 Object.
                        try {
                             system = new AS400(systemName, userName, password);
                             system.connectService(AS400.SIGNON);
                        catch (AS400SecurityException as400e) {
                             as400e.toString();
                        catch (IOException ioe) {
                             ioe.toString();
                        //Going to hide the Sign On window now.
                        setVisible(false);
                        //Now we will load the class that monitors
                        //the input and output queues.
                        MonitorDataQueueGui monitorGui = new MonitorDataQueueGui(system, inputQueue, outputQueue);
                        monitorGui.addGui();
                        monitorGui.show();
                        monitorGui.pack();
         public static void main(String[] args)
              SignOn signOn = new SignOn();
              signOn.loadGui();
              signOn.setSize(400, 400);
              signOn.show();
              signOn.pack();
              signOn.setVisible(true);
              signOn.addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent e)
                        System.exit(0);
    }

    Well....I ended up using insertRow with the following code within the method.
         public void insertRow(){      
              numRows += 1;
              fireTableDataChanged();
    I changed my method for the getRowCount to the following;
         * @see javax.swing.table.TableModel#getRowCount()
         public synchronized int getRowCount()
              if (numRows < START_NUM_ROWS)
                   numRows = START_NUM_ROWS;
                   return START_NUM_ROWS;
              else
                   return numRows;
    Since I am not scared of deleting rows I think this is fine....After I did this within my SignOn class I have the following within my TableListener inner class.
         private class TableListener implements TableModelListener {
    public TableListener() {
    public void tableChanged(TableModelEvent e) {
    int row = e.getFirstRow();
    int column = e.getColumn();
    String columnName = tableModelInputQueue.getColumnName(column);
    Object data = tableModelInputQueue.getValueAt(row, column);
    System.out.println("row " + row + "column " + column);
    if (row > 4) {
         tableModelInputQueue.insertRow();
    I am wondering if this is the best way to do it. It seems to work now without a problem but like I said...I am wondering if this is the best thing to do. Any advise would be greatly appreciated and I really do appreciate the advise that has already been given to me.

  • How do I add a new row to an AbstractTableModel?

    I'm having an issue with adding new data to a table row. Every row I add contains the same data which is always the last data I grabbed from my database. I'm not sure if my issue has to do with how I set up the data to be passed or the table itself or both... Any help would be appreciated. It seems like the tablemodel is holding the memory spot ArrayList I'm passing. If I have to set up an arraylist of arraylists, to pass how do I do that?
    My output is always:
    1,4,Laser,10,120,100
    1,4,Laser,10,120,100
    1,4,Laser,10,120,100
    1,4,Laser,10,120,100
    Desired output:
    1,1,Beam,10,99,100
    1,2,Canon,10,120,100
    1,3,Missile,10,66,100
    1,4,Laser,10,120,100
         * Extract weaponIDs by hullType from weapon database
    private void setWeapons(int hullType){
    // equpModel is the tableModel
        equipModel.clearTable();
        Weapon tempWeapon = new Weapon();
        ArrayList newData = new ArrayList();
        for (Iterator <Weapon> i = dataBaseManager.weaponList.iterator(); i.hasNext(); ){
            tempWeapon = i.next();
            if (tempWeapon.weaponClass == hullType){
                newData.add(0,1);
                newData.add(1,tempWeapon.weaponID);
                newData.add(2,tempWeapon.weaponName);
                newData.add(3,tempWeapon.weaponCps);
                newData.add(4,tempWeapon.weaponMass);
                newData.add(5,tempWeapon.weaponCost);
                equipModel.insertRow(newData);
    }Here is a snipet from the table class
    public class GenTableModel extends AbstractTableModel {
      private ArrayList data; // Holds the table data
      private String[] columnNames; // Holds the column names.
       * Constructor: Initializes the table structure, including number of columns
       * and column headings. Also initializes table data with default values.
       * @param columnscolumns[] array of column titles.
       * @param defaultvdefaultv array of default value objects, for each column.
       * @param rowsrows number of rows initially.
      public GenTableModel(String[] columns, Object[] defaultv, int rows) {
        // Initialize number of columns and column headings
        columnNames = new String[ columns.length ];
        for(int i = 0; i < columns.length; i++) {
          columnNames [ i ] = new String(columns [ i ]);
        // Instantiate Data ArrayList, and fill it up with default values
        data = new ArrayList();
        for(int i = 0; i < rows; i++) {
          ArrayList cols = new ArrayList();
          for(int j = 0; j < columns.length; j++) {
            cols.add(defaultv [ j ]);
          data.add(cols);
       * Adds a new row to the table.
       * @param newrowArrayList new row data
      public void insertRow(ArrayList newrow) {     
        data.add(newrow);
        super.fireTableDataChanged();
       * Clears the table data.
      public void clearTable() {
        data = new ArrayList();
        super.fireTableDataChanged();
    }

    Hi thanks again for responding
    Here is the Initialization, including the panel and scrollpane it sits on.
          // Table attempt
            JPanel tablePanel = new JPanel(new BorderLayout());
            tablePanel.setBounds(PANEL_X+2*PANEL_DISTANCE, PANEL_Y, PANEL_WIDTH+300, PANEL_HEIGHT);
            title = BorderFactory.createTitledBorder(blackLine, "Table List");
            tablePanel.setBorder(title);
    // This is column tile plus one dummy initilization set.
            String[] columnNames = {"DB", "ID", "Name", "CPS", "Energy", "Mass", "Cost"};
            Object[] data = {new Integer(0),new Integer(0), "Empty", new Integer(0),
                        new Integer(0),new Integer(0),new Integer(0)};
    // here is the GenTableModel creation
            equipModel = new GenTableModel(columnNames, data, 1);
            equipmentTable = new JTable(equipModel);
            equipmentTable.setRowSelectionAllowed(true);
            equipmentTable.setFillsViewportHeight(true);
            equipmentTable.setColumnSelectionAllowed(false);
            TableColumn column = null;
            column = equipmentTable.getColumnModel().getColumn(0);
            column.setPreferredWidth(20);
            column = equipmentTable.getColumnModel().getColumn(1);
            column.setPreferredWidth(20);
            JScrollPane scrollPane = new JScrollPane(equipmentTable);
            tablePanel.add(scrollPane);
            add(tablePanel);
        Here is the full code for GenTableModel. It is as you guessed.
    public class GenTableModel extends AbstractTableModel {
      private ArrayList data; // Holds the table data
      private String[] columnNames; // Holds the column names.
      public GenTableModel(String[] columns, Object[] defaultv, int rows) {
        // Initialize number of columns and column headings
        columnNames = new String[ columns.length ];
        for(int i = 0; i < columns.length; i++) {
          columnNames [ i ] = new String(columns [ i ]);
        // Instantiate Data ArrayList, and fill it up with default values
        data = new ArrayList();
        for(int i = 0; i < rows; i++) {
          ArrayList cols = new ArrayList();
          for(int j = 0; j < columns.length; j++) {
            cols.add(defaultv [ j ]);
          data.add(cols);
      public int getColumnCount() {
        return columnNames.length;
      public int getRowCount() {
        return data.size();
      public String getColumnName(int col) {
        return columnNames [ col ];
      public Object getValueAt(int row, int col) {
        ArrayList colArrayList = (ArrayList) data.get(row);
        return colArrayList.get(col);
      public Class getColumnClass(int col) {
        // If value at given cell is null, return default class-String
        return getValueAt(0, col) == null ? String.class
                                          : getValueAt(0, col).getClass();
      public void setValueAt(Object obj, int row, int col) {
        ArrayList colArrayList = (ArrayList) data.get(row);
        colArrayList.set(col, obj);
      public void insertRow(ArrayList newrow) {     
        data.add(newrow);
        super.fireTableDataChanged();
      public void deleteRow(int row) {
        data.remove(row);
        super.fireTableDataChanged();
      public void deleteAfterSelectedRow(int row) {
        int size = this.getRowCount();
        int n = size - (row + 1);
        for(int i = 1; i <= n; i++) {
          data.remove(row + 1);
        super.fireTableDataChanged();
      public ArrayList getRow(int row) {
        return (ArrayList) data.get(row);
      public void updateRow(ArrayList updatedRow, int row) {
        data.set(row, updatedRow);
        super.fireTableDataChanged();
      public void clearTable() {
        data = new ArrayList();
        super.fireTableDataChanged();
    }

  • Deleting a row from a JTable using AbstractTableModel

    Hi,
    Can someone please help me on how should i go about deleting a row in a jtable using the AbstractTableModel. Here i know how to delete it by using vector as one of the elements in the table. But i want to know how to delete it using an Object[][] as the row field.
    Thanks for the help

    Hi,
    I'm in desperate position for this please help

  • How do i select a particular cell from a AbstractTableModel?

    I m using abstractTableModel to create my table. My table display 4 columns of different info, now i can capture my info from the other window and compare the value with my table but i don't know how to highlight/or select the particular rows in table.

    Hi,
    as I said before, the changeSelection(...) method of JTable will setup it's ListSelectionModel so that the row, you want, gets selected/highlighted:
    yourTable.changeSelection(row,0,false,false);
    will select a certain cell - but if selection of a single cell is not allowed and row selection is allowed, the whole row will be selected this way. You can allow selection of a single cell, selection of a column, selection of a row, or simultaneous selection of column and row at the same time. You can have single selection and multi selection.
    Hope this helps
    greetings Marsian

  • AbstractTableModel-- Delete a row (pls help.....)

    Hi !
    I have a JTable of AbstractTableModel. now if i have to delete a row how can I ?
    pls post a sample code...
    FYI : This is my JTable
    class ViewTable extends AbstractTableModel{
        private String[] columnNames = {"COMP",
                                        "FILE NAME",
                                        "FILE LOCATION",
                                        "HOT #",
                                        "APPLIED ON",
                                        "DELETE"};
        private Object [][] data  = new Object [50][6];
        private Class types[]=new Class[]{ String.class,String.class,String.class,String.class,String.class,Boolean.class};
        public  void setValues()
             for(int i=0;i< data.length;i++)
                  data[0]=null;
              data[i][1]=null;
              data[i][2]=null;
              data[i][3]=null;
              data[i][4]=null;
              data[i][5]=new Boolean(false);
    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 types[c];
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col < 2) {
    return false;
    } else {
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    I create the Table like this...ViewTable VT= new ViewTable();
    view_table = new JTable(VT);

    dashok.83 wrote:
    yes.. How can I have the last column as checkBox....Make the last column boolean. You should extend the DefaultTableModel class and override the getColumnClass to return the appropriate class to get the appropriate behaviour (for instance I think that it's Boolean.class to get a check mark). Have you looked through the Sun tutorials on this? You should do this before asking the question here.

  • Javadoc bug or missing an option for class extending AbstractTableModel

    Hi Everybody,
    I am reviewing my javadoc before submission of my SCJD assignment and I noticed
    for my JTable model class HotelRoomTableModel that extends AbstractTableModel
    for all the overwritten methods like getValueAt(), getColumnCount(), getRowCount()
    that implement the TableModel interface where I am using javadoc comments of the form:
    * {@inheritDoc}
    @Override the HTML generated javadoc I see in my browser doesn't show anything
    for these methods other than the name and the signature of the method.
    Is that normal? Or is it a bug? Or perhaps did I miss anything?
    I would hope that it would show something like:
    "Specified by: methodName in interface InterfaceName"
    or
    "Overrides: methodMame in class ClassName".
    My environment:
    [auyantepui]</home/morillo/src/java/scjd/submission>% java -version
    java version "1.6.0_18"
    Java(TM) SE Runtime Environment (build 1.6.0_18-b07)
    Java HotSpot(TM) Server VM (build 16.0-b13, mixed mode)
    [auyantepui]</home/morillo/src/java/scjd/submission>% cat /etc/release
                           Solaris 10 5/09 s10s_u7wos_08 SPARC
               Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
                            Use is subject to license terms.
                                 Assembled 30 March 2009
    [auyantepui]</home/morillo/src/java/scjd/submission>% uname -a
    SunOS auyantepui 5.10 Generic_139555-08 sun4u sparc SUNW,Sun-Blade-1000
    [auyantepui]</home/morillo/src/java/scjd/submission>%Any ideas?
    Thanks,
    Carlos.

    He quoted the Javadoc which says you have to have the source code available for the Javadoc you are trying to inherit. All I am doing here is restating that, which really is pointless and valueless.It needs the source so that it can copy the documentation you want to copy, which I would have thought was obvious in the first place >
    ejp, there is no need to be such an arrogant jerk responding. It is not my fault if you are having a bad day.
    I wrote above:
    TableModel interface is in javax.swing.table. It is not part of my source code.I am only asking for help and I thought that was the purpose of this forum.
    I am not here to get a smart ass response with such an arrogance and attitude.

  • Pass a value to a class that extends AbstractTableModel

    Hi
    I have a problem with a table model that I cannot find a way of overcoming.
    I have created a class called MyTableModel that extends AbstractTableModel.
    MyTableModel creates and uses another class that I have defined in order to retrieve records from a database, MyTableModel fills the table with these records.
    However, I wish to alter my class in order to provide an int parameter that will act as a �where� value in the classes sql query.
    The problem is this, I cannot work out how to pass a value into MyTableModel. I have tried creating a simple constructor in order to pass the value but it doesn�t work.
    My code is shown below:
    import BusinessObjects.JobItemClass;
    import DBCommunication.*;
    import java.util.ArrayList;
    import javax.swing.table.AbstractTableModel;
    public class MyJobItemTableModel extends AbstractTableModel
      public MyJobItemTableModel(int j)
          jobNo = j;
      int jobNo;
      JobAllItems jobItems = new JobAllItems(jobNo);
      ArrayList items = jobItems.getItems();
      String columnName[] = { "Item Number", "Item Description", "Cost per item", "Quantity" };
      int c = items.size();
      Class columnType[] = { Integer.class, String.class, Double.class, Integer.class };
      Object table[][] =  new Object[c][4];
      public void fillTable()
          if(c > 0)
            for (int i = 0; i < c; i = i + 1)
              this.setValueAt(((JobItemClass) items.get(i)).getItemNumber(), i, 0);
              this.setValueAt(((JobItemClass) items.get(i)).getDescription(), i, 1);
              this.setValueAt(((JobItemClass) items.get(i)).getCostPerItem(), i, 2);
              this.setValueAt(((JobItemClass) items.get(i)).getQuantity(), i, 3);
      public void setJobNo(int s)
          jobNo = s;
      public int getColumnCount()
          if(c > 0)
            return table[0].length;
          else
              return 0;
      public int getRowCount()
        return table.length;
      public Object getValueAt(int r, int c)
        return table[r][c];
      public String getColumnName(int column)
        return columnName[column];
      public Class getColumnClass(int c)
        return columnType[c];
      public boolean isCellEditable(int r, int c)
        return false;
      public void setValueAt(Object aValue, int r, int c)
          table[r][c] = aValue;
    }Any advice will be appreciated.
    Many Thanks
    GB

    your JobAllItems is created before constructor code is run (since it is initialized in class member declaration)
    use something like
    public MyJobItemTableModel(int j)
          jobNo = j;
          items = (new JobAllItems(jobNo)).getItems();
          c = items.size();
          table =   new Object[c][4];
      int jobNo;
      ArrayList items;
      String columnName[] = { "Item Number", "Item Description", "Cost per item", "Quantity" };
      int c;
      Class columnType[] = { Integer.class, String.class, Double.class, Integer.class };
      Object table[][] ;instead of
    public MyJobItemTableModel(int j)
          jobNo = j;
      int jobNo;
      JobAllItems jobItems = new JobAllItems(jobNo);
      ArrayList items = jobItems.getItems();
      String columnName[] = { "Item Number", "Item Description", "Cost per item", "Quantity" };
      int c = items.size();
      Class columnType[] = { Integer.class, String.class, Double.class, Integer.class };
      Object table[][] =  new Object[c][4];

  • MySQL+JTable, AbstractTableModel - solution v.0.1 beta

    Hi everybody, My name is Sergey, I am a student from Russian Federation, Moscow.
    I spent days and nights trying to find how to connect JTable, DB tables.
    To tell you the truth, I visited many russian and english-lang forums. But I didn't get somewhere goog answer. that is terrible.
    Seems like nobody nows how to do simple things.
    So, I've started to do on my own. And I suggest you the first version.
    Ofcourse it is rather raw, but it works.
    Sometimes I was really angry when people suggested others untested and foolish code. With mistakes.
    what we need:
    JDBC adapter - mysql.com (you canget it)
    MySQL server (must be started)
    DB
    Tables in DB
    NetBeans 5.5 - netbeans.org
    NB MySQL server on localhost, thisway you will not need to dig mysql config files
    Create new project application
    Add mysql driver jar file to project library (it is in project window)
    create two classes and enjoy
    import java.sql.*;
    import java.util.Collections;
    import java.util.List;
    import java.util.Vector;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.table.AbstractTableModel;
    import java.util.Collections;
    * @author SShpk
    //we are going to override methods of AbstracTableModel Class
    /**This class forms view of DB table which will be loaded into JTable swing component*/
    public class JTableAdapter extends AbstractTableModel{
            //my table name
            private String tableName ="Sheet";
         //frame for error exception output
            private JFrame jframeError = new JFrame("Connection error");
            //variables for transactions
            private Connection connection;
            private Statement  statement;
            private ResultSet  resultSet;
            private ResultSetMetaData metaData;
            //names of colums --- will get them from DB table
            public  String[]   columnNames;
            //this Vector will  keep rows of table
            private Vector     rows = new Vector();
            private int i;
            private String t="";
        /** Creates a new instance of JTableAdapter */
        public JTableAdapter(String url, String driverName, String user, String password) {
            jframeError.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//frame for showing errors
            //this String var I use to avoid problem with Date/Datestamps e.t.c. like �0000-00-00�
         //because java converts them to NULL. This is terrible fact. Do not lose this comment!
            String overrideBADDATE="zeroDateTimeBehavior=convertToNull&";
         //let�s put together all params
            //common view is: :jdbc:mysql://yourhost.com:port_num/NameofYourDB?<property&>
            t=url+overrideBADDATE+"user="+user+"&password="+password;
            try{     //trying to load driver
                Class.forName(driverName);
                connection=DriverManager.getConnection(t);
                statement = connection.createStatement();
                                    //this commented code will be useful for you in debug proccess.
                                    //it will give you list of all loaded drivers to driver managers
                                    //so you will be able to see is your jdbc driver loaded or not.
                                     try{
                                          List drivers = Collections.list(DriverManager.getDrivers());
                                          for(int i=0;i<drivers.size();i++){
                                              Driver driver = (Driver)drivers.get(i);
                                              String driverName1 = driver.getClass().getName();
                                              System.out.println("Driver "+i+":::"+driverName1);
                                     }catch(Exception e){
                                          System.out.println(e);
                                     }//catch in try
            }//try
            //let's catch exceptions.
            //see messages to get the meaning of exception
            catch(ClassNotFoundException ex){
                         JOptionPane.showMessageDialog(jframeError,
                                                        "Error occurred during driver load"+driverName,
                                                        "Driver load error:"+ex.getMessage(),
                                                        JOptionPane.ERROR_MESSAGE);
                                                        jframeError.setVisible(true);
            }//catch1
            catch(SQLException ex){
                         JOptionPane.showMessageDialog(jframeError,
                                                        "Error connecting DB"+url,
                                                        "DB Connection error:"+ex.getMessage(),
                                                        JOptionPane.ERROR_MESSAGE);
                                                        jframeError.setVisible(true);
            }//catch2
        //executing SELECT query to fill our table
         executeQuery("SELECT * FROM " + this.tableName);  
        }//constructor
        /**method sends SELECT query and parses result of this query*/
        public void executeQuery(String query){
            //testing for alive connection
            if(connection== null || statement == null){
                            JOptionPane.showMessageDialog(jframeError,
                                                        "Error occurred during query post",
                                                        "DB connection error",
                                                        JOptionPane.ERROR_MESSAGE);
                                                        jframeError.setVisible(true);
         //let�s parse result of query
            try{
                resultSet = statement.executeQuery(query);
                //get num of columns in table   /***/getColumnCount()
                //get names of columns          /***/getColumnLabel(i+1)
                metaData = resultSet.getMetaData();
                int numberOfColumns = metaData.getColumnCount();
               //getting names of DB table columns
                columnNames = new String[numberOfColumns];
                for(i=0;i<numberOfColumns;i++){
                        columnNames= metaData.getColumnLabel(i+1);
    }//for
    Object testnulledobj;
    rows = new Vector();
    //from the beginning of resultSet up to the END
    while (resultSet.next()){
    //each row of DB table is Vector
    Vector newRow = new Vector();
    for (i=1; i<= getColumnCount();i++){
    testnulledobj=resultSet.getObject(i);
         //this IF statement I will develop
    //to output NULL-object Date (like Date field = 0000-00-00)
    if(resultSet.wasNull()){
    testnulledobj=new String("");
    newRow.addElement(testnulledobj);
    }//for
              //row from DB is completed. Every row will be in Vector of Rows.
              //I hope you got my idea.
              //We collect row cells of DB table row in Vector
              //Then we put this Vector into another Vector, which consists of DB rows
    rows.addElement(newRow);
    }//while
    //table is changed
    fireTableChanged(null);
    }//try
    catch(SQLException ex){
    JOptionPane.showMessageDialog(jframeError,
    "Error occurred during query result parsing",
    "Data accept error",
    JOptionPane.ERROR_MESSAGE);
    jframeError.setVisible(true);
    }//executeQuery
    /**cell of table editable or not?*/
    public boolean isCellEditable(int row,int column){
    /*Testing field(aka column) property. We get it from DB.
    try{
    return metaData.isWritable(column+1);
    }//try
    catch(SQLException e){
    return false;
    }//catch
    /****LOCKING ID FIELD***/
    if(column>0) return true;
    else return false;
    }//isCellEditable
    //these three methods very simple. I think they do not need any explanations
    /**set column name in JTable*/
    public String getColumnName(int column){
    return this.columnNames[column];
    /**get quantity of rows in table*/
    public int getRowCount(){
    return this.rows.size();
    /**get quantity of columns in table*/
    public int getColumnCount(){
    return this.columnNames.length;
    /**get value from JTable cell*/
    public Object getValueAt(int aRow, int aColumn){
    Vector row = (Vector)rows.elementAt(aRow);
    return row.elementAt(aColumn);
    //if user edited cell (double-click on it and then went away)
    //we need to update DB table and JTable also.
    //this is not pretty good variant, because we will flood DB with plenty of small queries.
    //the best way is to save value of "double-clicked" cell. Then we have to compare its value before
    //focus and after. If values differ, then we update DB table, else � no update
    //unfortunately I do not know how to control focus method of JTable cell
    /**update DB table cell value*/
    public void setValueAt(Object value, int row, int column){
    //Before updating DB table cell we need to update JTable cell
    Object val;
    val = tbRepresentation(column, value);
    Vector dataRow = (Vector)rows.elementAt(row);
    dataRow.setElementAt(val,column);
    //Now it's time to update DB table
    try{
    //get name of column in DB table (our JTable has the same column names)
    //it's possible to give them normal names instead of user_id,user_name e.t.c.
    //I am sure, user of your app will prefer to see normal names of columns, not like listed before
    String columnName = getColumnName(column);
    //This is very bad example of update query.
    //You have to determine automatically key field. but still I didn't find how to do that
    //But it's possible to do through metadata. I am sure.
    //Just need some more time
    //When I am designing DB I prefer to name key field in each table as "ID"
    String query = "UPDATE "
    tableName
    " SET "+columnName+" = "+"'"+dbRepresentation(column,getValueAt(row, column))+"'"+
    " WHERE ID = "+dbRepresentation(0,getValueAt(row, 0));
    //extremely important string for debug
    System.out.println("UPDATE QUERY:::"+query);
    //executing update query
    PreparedStatement pstmt = connection.prepareStatement(query);
    pstmt.executeUpdate();
    }//try
    catch(Exception ex){
    JOptionPane.showMessageDialog(jframeError,
    "������ ��� ���������� ������ � ������� ��",
    "������ �������� ��� ���������� ������ � ��",
    JOptionPane.ERROR_MESSAGE);
    jframeError.setVisible(true);
    }//catch
    }//setValueAt
    //Next two methods are very neccessary. And they need accurate testing
    //they convert DB datatypes into java datatypes and backwards
    /**convert SQL (MySQL in this case) datatypes into datatypes which java accepts*/
    public Object tbRepresentation(int column, Object value) throws NumberFormatException{
    Object val;
    int type;
    if(value == null){
    return "null";
    }//if null
    try{
    type = metaData.getColumnType(column+1);
    }//try
    catch (SQLException e){
    JOptionPane.showMessageDialog(jframeError,
    "Error occured during Table update",
    "Error occured during DB table field type get",
    JOptionPane.ERROR_MESSAGE);
    jframeError.setVisible(true);
    return value.toString();
    }//catch
    switch(type){
    case Types.BIGINT:
    return val = new Long(value.toString());
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    return val = new Integer(value.toString());
    case Types.REAL:
    case Types.FLOAT:
    case Types.DOUBLE:
    case Types.DECIMAL:
    return val = new Double(value.toString());
    case Types.CHAR:
    case Types.BLOB:
    case Types.VARCHAR:
    case Types.LONGNVARCHAR:
    return val = new String(value.toString());
    case Types.DATE:
    return val = new String(value.toString());
    default: return val = new String(value.toString());
    }//switch
    }//tbRepresentation
    /**conver Java datatypes into SQL (MySQL) datatypes*/
    public Object dbRepresentation(int column, Object value){
    Object val;
    int type;
    if(value == null){
    return "null";
    }//if null
    //my preparations for accurate work with "nulled" dates/time/e.t.c
    //this IF statement doesn't play any important role
    String testbaddate="0000-00-00";
    if(value.toString().equals(testbaddate)){
    return value.toString();
    try{
    type = metaData.getColumnType(column+1);
    }//try
    catch (SQLException e){
    return value.toString();
    }//catch
    switch(type){
    case Types.BIGINT:
    return val = new Long(value.toString());
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    return val = new Integer(value.toString());
    case Types.DECIMAL:
    case Types.FLOAT:
    case Types.DOUBLE:
    return val = new Double(value.toString());
    case Types.VARCHAR:
    case Types.CHAR:
    return val = new String(value.toString());
    case Types.DATE:
    return val = new String(value.toString());
    default: return val = new String(value.toString());
    }//switch
    }//dbRepresentation
    //my preparations to read from SELECT query result
    //"nulled" dates/time/e.t.c.
    private Object testObject(Object obj){
    Object val= new String("");
    if(obj==null) return new String(val.toString());
    else return obj;
    }//class
    And other class. I will not comment it.
    It is very easy. Ask me if you want something
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class TableCreate extends JPanel{
        /** Creates a new instance of TableCreate */
        public TableCreate() {
            super(new GridLayout(1,0));
            JTable table = new JTable(new JTableAdapter("jdbc:mysql://localhost/Document?","com.mysql.jdbc.Driver","root",""));
            table.setPreferredScrollableViewportSize(new Dimension(500,210));
            JScrollPane scrollpane = new JScrollPane(table);
            add(scrollpane);
        public JPanel getJpanelTable(){
            return this;
        public static void main(String[] args){
            JFrame jframe = new JFrame("Test");
                TableCreate tcreate = new TableCreate();
                    jframe.add(tcreate.getJpanelTable());
                    jframe.pack();
                    jframe.setVisible(true);
    }//main

    So what we have:
    -DB table insert into JTable
    -Can edit values+update them in DB
    -override some common "critical points"
    What we need:
    -control row,col size in JTable
    -control column names in JTable
    -add combobox on fields which keep ID of other instance (I will give test example later)
    -add checkbox to boolean fields and to boolean fields which declared as int-family type, but use only "0" and "1" numbers
    -Add sort to JTable (to its header)
    -Add conrol buttons
    --new row
    --delete row
    --next record
    --previous record
    -Add user friendly GUI (highlight selected row e.t.c.)
    So as you can see, a lot of things to do
    I will be happy to answer all you questions
    But if you want to make me really happy- comment my post and suggest me how to refact code and approach this JTableAdapter class to reusable component (I want it to be useful in common cases when Java-specialist work with DB especially with MySQL)

  • Please help - AbstractTableModel, result set and JTable

    Pls help me on this:
    I derive a new class, myTable that extends the AbstractTableModel, one of the member method is like this:
    public void setValueAt( Object data, int row, int col ){
    try{
    resultSet.absolute( row + 1 );
    resultSet.updateDouble( col + 1, Double.parseDouble( data.toString()));
    resultSet.updateRow();
    }//end try
    catch( SQLException sqlEx ){
    JOptionPane.showMessageDialog( null, "SQL error", "", 1 );
    Everytime i try to update the data( which is double), example 2.00, i will see this runtime error:
    java.lang.NumberFormatError: 2.00
    The database is Microsoft Access 2000 and OS is Win ME. I update the data by using JTable GUI( which extends the new class myTable).
    When i try to use Oracle database, then there is no problem for this.
    How to solve this problem?

    can i get a look at your TableModel for the JTable.
    Your problem with Access: Access "double" is not the same as
    Oracle's double.
    you can try the various types that have decimals until you find
    which one access will accept.

  • How to delete a row from AbstractTableModel

    my table is using an object to populate the data.
    static Object[][] data = new Object[LineCount()][5];
    So when I delete a row, I should delete from the model or the object?
    Rgds

    When you populate your table with a two dimensional array, the table actually creates a DefaultTableModel (which extends AbstractTableModel). The DefaultTableModel has methods which allow you to add/remove row from the data model. Read the DefaultTableModel API for more information.

  • Need help serializing an AbstractTableModel for a JTable with cell editing.

    Fun times are ahead. Here we go!
    I have a JTable that contains data I'd like to serialize out to a file to be restored and viewed later.
    So I tried saving the AbstractTableModel subclass out to a file. Whenever I do this, I get the following error message:
    java.io.NotSerializableException: javax.swing.JTable$CellEditorRemover
    Now I know for fact that serializing an AbstractTableModel that was installed in a JTable without cell editing works just fine (my old code did exactly that). As a result, I think that the code that handles events in the AbstractTableModel contains references back out to the JTable, which causes the JTable to be saved no matter what (even though I'm just interested in saving the TableModel only). It causes a bigger file than normal, but file size is not an issue. The only issue I have is that CellEditorRemover (an undocumented inner class of JTable), which is automatically installed for JTables with editable cells, is not serializable.
    This leads to the following questions:
    1. Is there a way to avoid serialization/deserialization of the CellEditorRemover inner class of JTable?
    2. Is there a way to save an AbstractTableModel without saving all of the event listeners associated with it?
    I think an answer to either of these questions would go a long way towards solving my problem. Otherwise, I'll resign myself to weeping silently in the corner of my office.
    Thanks!

    I would suggest that if you can you only save the
    data... but i would do this by using the
    externalizable interface.
    What you will need to do is have the
    writeExternal(ObjectOutputStream out) and
    readExternal(ObjectOutputStream out) methods in your
    class. These will be responsiable for saving the
    data.
    Here's an example of what you can do in these
    methods... this is just a little tidbit from a program
    i've written.public void writeExternal(ObjectOutput out) throws
    IOException {
              out.writeInt(size);
              out.writeObject(drawName);
              out.writeInt(playersLength);
    for(int i = 0; i < playersLength; i++)
    ) out.writeObject(players);
              out.writeInt(seedsLength);
    for(int i = 0; i < seedsLength; i++)
    ) out.writeObject(seeds[i]);
              out.writeInt(drawLength);
    for(int i = 0; i < drawLength; i++)
    ) out.writeObject(draw[i]);
    public void readExternal(ObjectInput in) throws
    IOException, ClassNotFoundException {
              size = in.readInt();
              drawName = (String)in.readObject();
              playersLength = in.readInt();
    for(int i = 0; i < playersLength; i++) players[i] =
    = (String)in.readObject();
              seedsLength = in.readInt();
    for(int i = 0; i < seedsLength; i++) seeds[i] =
    = (String)in.readObject();
              drawLength = in.readInt();
    for(int i = 0; i < drawLength; i++) draw[i] =
    = (String)in.readObject();
    You can now use your class as you would a Serializable
    class, but it will only save the data
    Hope this helped
    webaf409java
    I forgot to add some critical information in my original post. My apologies. :(
    I've thought about using Externalizable, but am hesitant to use it because the application would no longer be able to read in files using the old save format (ie, AbstractTableModels for JTables without CellEditorRemovers ).  I want to preserve the ability to read the old saved AbstractTableModel formats if possible. 
    Do you know of a way to revert to the default deserialization mechanism from readExternal?  This way, during deserialization, I could do a quick test on the object being read and have the ability to default to the regular deserialization mechanism if the object is of the old type or continue with the new Externalizable stuff if the object is one of the new type.  Maintaining file compatibility is key.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to use AbstractTableModel in JTable

    hi
    i want how to use AbstractTableModel in Jtable
    plz give code

    Multi-post: http://forum.java.sun.com/thread.jspa?threadID=5273661&tstart=0

  • Storing data in AbstractTableModel

    hi,
    i have a program that uses AbstractTableModel with Jtable....I need to store data in a file when the program closes... i heard that there is a way to some how convert data in Tablemodel to a binary file and retrieve data from the binary file...other then storing it in a text file and parsing the data. So can anyone help me?
    Thanks

    Hi missKip,
    As far as I know, class "javax.swing.table.AbstractTableModel" is abstract, so your "JTable" must be using a class that extends "AbstractTableModel".
    In any case, writing and reading from a file -- with java -- has nothing to do with "JTable"s and/or "AbstractTableModel"s -- it has to do with the classes in package "java.io". Are you not familiar with these classes or how to use them?
    Unfortunately, based on the [lack of] information you have provided, I cannot give you any details on the sort of code you need to write, I can only point you at resources (that I assume you are unfamiliar with) that may help you:
    http://java.sun.com/docs/books/tutorial/essential/io/index.html
    http://developer.java.sun.com/developer/technicalArticles/Streams/
    http://www.oreilly.com/catalog/javaio/
    Hope this helps you.
    Good Luck,
    Avi.

  • Table - Storing data in a AbstractTableModel for a renderer

    I have a class which extends AbstractTableModel in which I am storing more than just the data which is displayed in each cell (i.e. metadata and other data which is specific to the cells are stored in private arrays).
    I also have a class which extends DefaultTableCellRenderer which colorises the cells. There are several tables and they all use the same class to do the rendering however I would like it if I could retreive the data from the TableModel class to decide on the color of a cell . If I have:
    private class calTableModel extends AbstractTableModel{
              public calTableModel() {
    ....Usual stuff
    public int AnotherMethod(){...}
    and I try this
    private class CustomTableCellRenderer extends DefaultTableCellRenderer
              public Component getTableCellRendererComponent
              (JTable table, Object value, boolean isSelected,
              boolean hasFocus, int row, int column)
    table.getModel().AnotherMethod()
    then I get a cannot resolve symbol error.
    How do I extend the interface as well as the class so I can call my other methods in this way?
    Many thanks in advance.

    You have to cast to your tableModel:private class CustomTableCellRenderer extends DefaultTableCellRenderer
    public Component getTableCellRendererComponent
    (JTable table, Object value, boolean isSelected,
    boolean hasFocus, int row, int column)
    ((calTableModel )table.getModel()).AnotherMethod(); // cast to calTableModel

Maybe you are looking for

  • Need to run 2 versions of FF, diferent privacy settings

    I have FF12 and it is set up the way I want it to so I feel that my anonymity is protected. Problem is now I am starting to do research and I need to have different privacy settings. Is there a way to run 2 versions of FF AND have different privacy s

  • Running matlab program via switch in labview

    Hi, I had a basic question on integrating a matlab m file into labview. What I pretty much want is the ability to run a certain m file at a flip of a switch. I essentially created a reset button and that reset button will reset my device.  I attached

  • ORA-02266: unique/primary keys in table referenced by enabled foreign keys

    Hi, I am trying to delete data from a table by dropping a partition. I have identified all the child tables by running the following command. select 'select count(*) from '||table_name||' where employee_id = 100;' from dba_constraints where constrain

  • My charger port wont work what do i do?

    Last night i put my ipod away in my bad (there was nothing in it) and it stopped charging this morning. I bought a new charger and everything. I know that i didnt break any part in the charger port but im not sure what to do. My ipod is on low batter

  • How to set the Paper TYPE?

    We have HP Multifunction printers here at work, example the HP Laserjet 4345 MFP. In Output Designer I have no problem setting the Presentment Target, almost always just set it to HP Laserjet 8000/8000N (PCL5). My problem is that I can control the tr