Insertion in a DefaultTableModel

I have made a DefaultTableModel which has rows and columns (in a format like a excel sheet which has DATES in the rows and TIMES in the columns like a calender) and i want to enter some string data on the cells which will be stored somehow, in a database which has records of type : DATE TIME TEXT.
Any ideas how can i get the data from the cells of the table which will be a specific format of DATE-TIME-TEXT (STRING VALUE) and store them as a record in my database???
PLZ ANSWER ME BECAUSE IS VERY IMPORTAND FOR ME !

table.getModel().getValueAt(...);

Similar Messages

  • Insert column to DefaultTableModel

    How can I insert a new column of data, say between columns 4 and 5, to DefaultTableModel (not to JTable) ?

    and then want it to move to 3 position, I want that all the (old) columns 3,4,5,6,.... will move to the right. How can I manage it ? What have you tried? What problems did you encounter.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Can not insert data to MS Access

    Hi All,
    I have create a table by manual in Access , in which I defined souch fields:
    SORTCODE(text type),FOODNAME(text type)..., and then I use follow statement to insert value :
    private DefaultTableModel model = new DefaultTableModel();
    Vector collectData = new Vector(50,20);
    String sqlStatement = "INSERT ������(SORTCODE,FOODNAME,MEASUREUNIT,QUANTITY,UNITPRICE,BUYDATE,SUPPLIER,BUYER,HOTELNUM,HOTELNAME,REMARK) VALUES (?,?,?,?,?,?,?,?,?,?,?)";
    try
    PreparedStatement insertData = dbConnection.prepareStatement(sqlStatement);
    for(int i=0;i<rowsFlag;i++)
    for(int j=1;j<cols;j++)
    collectData.add(model.getValueAt(i,j));
    insertData.setString(1,collectData.get(0).toString());
    int update = insertData.executeUpdate(); //an Exception throwed
    catch(Exception ex)
    ex.printStackTrace();
    when run the code , it always reports Access field not correct error , how to solve the problem ?

    Hi Liwei,
    Apart from what marych said, according to the code you posted, you are only supplying one value to your "PreparedStatement", namely:
    insertData.setString(1,collectData.get(0).toString());You need to supply eleven values (in total), since your "sqlStatement" contains eleven question-mark ("?") characters.
    Also note that if one of the values you supply is null, then you need to use the "setNull()" method (of "PreparedStatement") and not the "setString()" method.
    Hope this helps.
    Good Luck,
    Avi.

  • Inserting a Row in to a JTable

    I have been looking and looking in the tutorials and other topics but can not find exactly what I need. I just need to start with a blank table and once something happens it will trigger to insert a row in to the table for updates.
    Here is the code on how I start the table.
    1. Object[] columnNames = {"Type", "Date", "Time", "Computer"};
    2. Object[][] rowData = {};
    3. errorTable = new JTable(rowData, columnNames);
    4. DefaultTableModel dtm = (DefaultTableModel)errorTable.getModel();
    5. dtm.setDataVector(rowData, columnNames);
    I get a ClassCastException on line 4.....why is that???

    Okay, so that worked to use DefaultTableModel.....but when i try and insert a row later on I get a null pointer exception when hitting line 7 below:
    //Getting computer name from the tree node
    1. String computer = getName(((DefaultMutableTreeNode) serverTree.getLastSelectedPathComponent )).getParent().toString(), "/");
    //Adding information to a vector to add to table
    2. dataVector.addElement("Information");
    3. dataVector.addElement("");
    4. dataVector.addElement("");
    5. dataVector.addElement(computer);
    6. holdVector.addElement(dataVector);
    //Hoping to insert the row here (but get null pointer)
    7. errorTableModel.setDataVector(dataVector, holdVector);
    What is the issue??? Do I need to do an insert row now or what? Thank you in advance.

  • Inserting Pics in a JTable

    I'd like to include an ID of the person within my table.
    Using DefaultTableModel and ImageIcon, how can I insert a picture?
    Is it even possible to enter a non-textual entry into a JTable?
    Here's what I did:
    JMenuItem insertPicture;
    JTable contactTable;
    DefaultTableModel details;
    else if(ae.getSource() == insertPicture)
      // Column and row details
      int row = contactTable.getSelectedRow();
      int column = contactTable.getSelectedColumn();
      // Using a string to store the picture's location details
      String fileName;
      FileDialog location = new FileDialog(ContactDetails.this,   
                "Choose picture", FileDialog.LOAD);
      // Displaying the FileDialog
      location.show();
      // Getting the image and inserting it in the JTable
      ImageIcon image = new ImageIcon(location.getDirectory()+
      location.getFile());
      details.setValueAt(image, row, column);
    }My problem is that within the row (to which the picture should be placed), I'm getting only the String description of the image's location. How can I correct this?
    Much thanks in advance!
    Reformer!

    import java.awt.*;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test {
        public static void main(String[] args) throws MalformedURLException {
            DefaultTableModel model = new DefaultTableModel(new String[]{"path","image"}, 0) {
                public Class getColumnClass(int columnIndex) {
                    return columnIndex==1? Icon.class : String.class;
                public boolean isCellEditable(int rowIndex, int columnIndex){
                    return false;
            URL[] urls = {
                new URL("http://today.java.net/jag/bio/JagHeadshot-small.jpg"),
                new URL("http://today.java.net/jag/bio/JAG2001small.jpg"),
                new URL("http://blogs.sun.com/roller/resources/jag/2005_09_14_03-44-21-438_n1.small.png")
            for(int i=0; i<urls.length; ++i)
                model.addRow(new Object[]{urls.toString(), new ImageIcon(urls[i])});
    JTable table = new JTable(model);
    table.setRowHeight(240);
    JScrollPane sp = new JScrollPane(table);
    sp.setPreferredSize(new Dimension(600,450));
    final JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(sp);
    f.pack();
    SwingUtilities.invokeLater(new Runnable(){
    public void run() {
    f.setLocationRelativeTo(null);
    f.setVisible(true);

  • Inserting row in JTable (runtime)

    i need to inserting row in JTable in runtime so tell me what it do

    dear farhanaj ,
    try this code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    /* <applet code=tableadd.class width=200 height=200>
    </applet>
    public class tableadd extends JApplet implements ActionListener
    Object[] data = new Object[5];
    DefaultTableModel defaulttablemodel = new DefaultTableModel();
    JTable jtable=new JTable(defaulttablemodel);
    JPanel jpanel= new JPanel();
    private     JPanel          topPanel,jpPanel;
    public     JTable          table;
    JButton jbutton1 = new JButton("create new row");
    JButton jbutton2 = new JButton("create new col");
    //JButton jbutton1=new Jbutton("r"),jbutton2=new Jbutton("c");
    public tableadd()
    for(int column=0 ; column<5 ; column++)
    defaulttablemodel.addColumn("column" + column);
    for(int row=0 ; row<5;row++)
    for(int column=0 ;column<5;column++)
    data[column]="cell" row "," + column;
    defaulttablemodel.addRow(data);
    //getContentPane().add(new JScrollPane(jtable) ,BorderLayout.CENTER);
    //getContentPane().add(new JPanel() ,BorderLayout.SOUTH);
    int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
    int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
    JScrollPane jsp = new JScrollPane(jtable , v, h);
    getContentPane().add(jsp, BorderLayout.CENTER);
    topPanel = new JPanel();
    jpPanel=new JPanel();
    topPanel.setLayout( new BorderLayout() );
    getContentPane().add(topPanel,BorderLayout.NORTH);
    getContentPane().add(jpPanel,BorderLayout.SOUTH);
    jpPanel.add(jbutton1);
    jpPanel.add(jbutton2);
    jbutton1.addActionListener(this);
    jbutton2.addActionListener(this);
    public void actionPerformed(ActionEvent e)
    if (e.getSource() == jbutton1)
    int numberrows = defaulttablemodel.getRowCount();
    int numbercolumns=defaulttablemodel.getColumnCount();
    Object[] data = new Object[numbercolumns];
    for(int column=0 ; column<numbercolumns;column++)
    data[column]="cell" numberrows "," +column;
    defaulttablemodel.addRow(data);
    else
    if (e.getSource() ==jbutton2)
    int numberrows=defaulttablemodel.getRowCount();
    int numbercolumns=defaulttablemodel.getColumnCount();
    defaulttablemodel.addColumn("column" + numbercolumns);
    for(int row=0; row<numberrows ; row++)
    defaulttablemodel.setValueAt("cell" row "," +numbercolumns ,row , numbercolumns);
                   System.out.println(row);
    //jtable.sizeColumnsToFit(0);

  • How to hightlight  the new  inserted data in the last low of JTable?

    Could somebody help me?
    i am doing the e-restaurant application system .
    When press the food button, the JTable will list out the order details.
    When the order is long, the scroll pane will show up.
    My problem is[ b] how to hightlight the new inserted data in the last low of JTable when the food button is press every time?The scroll pane will automatically scroll down the to the new insertted data.
    In the List, i get the effect like this command but in the JTable how?
    list.ensureIndexIsVisible(orderDetails.getSize()-1);
    thank in advance.
    Below is the snapshot of my coding:
    DefaultTableModel model=new DefaultTableModel(cells,columnNames);
    OrderModel sorter=new OrderModel(model);
    JTable table=new JTable(sorter);
    JScrollPane scrollPane=new JScrollPane();
    scrollPane.add(table);
    Object[] object={foodName, "1",price};
    model.addRow(object);
    sorter.fireTableDataChanged();
    sorter.fireTableStructureChanged();

    The right place to ask this one is "Swing Forum.
    http://forum.java.sun.com/forum.jspa?forumID=57

  • Insert empty row

    Hi all,
    I am trying to insert a new emty row to my JTable. After the new row is inserted the user should fill in the values.
    I tried inserting dummy data; it works fine. However, when I try to insert an empty Vector I get the following exception. Any reasons for this?
    //code
    //static MyTableModel myModel = new static MyTableModel(columnNames, data);
    TableDemo.myModel.addRow( new Vector() );
    java.lang.ArrayIndexOutOfBoundsException: 4 > 0
         at java.util.Vector.insertElementAt(Vector.java:558)
         at javax.swing.table.DefaultTableModel.insertRow(DefaultTableModel.java:347)
         at javax.swing.table.DefaultTableModel.addRow(DefaultTableModel.java:323)
         at project.ListenerCreateRecordButton.actionPerformed(ListenerCreateRecordButton.java:24)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1834)
         at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2152)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)

    Use the DefaultTableModel as is. I don't see any reason for you to extend it.
    This posting shows how to use the addRow method of the DefaultTableModel:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=577919

  • Insert a mysql resultset to a jTable

    Hi! I have a database which i can connect to and get information from, but i can't figure out how to insert my resultset into my jTable from two different classes, I found an good exaple on the web but i dont know how to split up the code. I work with the GUI editor in NEtbeans 6.8 since i'm most familiar with it.
    I have bound an jButton (that lies in Class A) that will call an method in Class B which will update the jTable.
    The action event code
    //Creates object "b" from the class ClassB
    ClassB b = new ClassB();
            try {
            //Call method showall in ClassB
            b.showall();
            } catch (ClassNotFoundException ex) {
    System.out.println("Class not found);
    {code}
    And here is the method "showall"
    {code}
            String sql = "my sql query";
            ResultSet rs = dc.query(sql);
            Object[] rows;
            while (rs.next()) {
             //add the values to the temporary row
            rows = new Object[]{rs.getInt(0), rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)};
            // add the temp row to the table
            // Startup is the name of my mainclass wich i have the jTable in (named "table")
          Startup.table.setValueAt(rows, 1, 1);
    {code}
    This is the example i found
    {code}
    class MySQLTable
      private static Connection con = null;
      private static String URL = "jdbc:mysql://localhost:3306";
      private static String driver = "com.mysql.jdbc.Driver";
      private static String user = "root";
      private static String pass = "";
       * Main aplication entry point
       * @param args
       * @throws SQLException
      public static void main(String[] args) throws SQLException
        // a MySQL statement
        Statement stmt;
        // a MySQL query
        String query;
        // the results from a MySQL query
        ResultSet rs;
        // 2 dimension array to hold table contents
        // it holds temp values for now
        Object rowData[][] = {{"Row1-Column1", "Row1-Column2", "Row1-Column3"}};
        // array to hold column names
        Object columnNames[] = {"ID", "User", "Password"};
        // create a table model and table based on it
        DefaultTableModel mTableModel = new DefaultTableModel(rowData, columnNames);
        JTable table = new JTable(mTableModel);
        // try and connect to the database
        try {
          Class.forName(driver).newInstance();
          con = DriverManager.getConnection(URL, user,pass);
        } catch (Exception e) {
          System.err.println("Exception: " + e.getMessage());
        // run the desired query
        query = "SELECT ID, User, Password FROM users.normal";
        // make a statement with the server
        stmt = con.createStatement();
        // execute the query and return the result
        rs = stmt.executeQuery(query);
        // create the gui
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JScrollPane scrollPane = new JScrollPane(table);
        frame.add(scrollPane, BorderLayout.CENTER);
        frame.setSize(300, 150);
        frame.setVisible(true);
        // remove the temp row
        mTableModel.removeRow(0);
        // create a temporary object array to hold the result for each row
        Object[] rows;
        // for each row returned
        while (rs.next()) {
          // add the values to the temporary row
          rows = new Object[]{rs.getString(1), rs.getString(2), rs.getString(3)};
          // add the temp row to the table
          mTableModel.addRow(rows);
      private MySQLTable()
    {code}
    I would appreciate some help with this :)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I am now close to my goal, no errors when i run my application but nothing happens to the jTable
    Here is the code for the method
        public void gettableinfo() throws ClassNotFoundException, SQLException{
            String sql = "sql query";
            ResultSet rs = DatabaseConnection.query(sql);
            Object[] rows;
            Startup.mTableModel.removeRow(0);
            while (rs.next()) {
            //add the values to the temporary row
            System.out.println(rs.getRow());
            rows = new Object[]{rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5)};
            // add the temp row to the table
            Startup.mTableModel.addRow(rows);
        }rs.getrow(); finds 12 rows, as i have in my database. but it dosent add the result to the table
    the code for the jTable:
    static Object rowData[][] = {{"Row1-Column1", "Row1-Column2", "Row1-Column3","Row1-Column4","Row1-Column5"}};
        // array to hold column names
      static Object columnNames[] = {"ID", "Name", "Info", "Type", "Material"};
      public static DefaultTableModel mTableModel = new DefaultTableModel(rowData, columnNames);since i'm using the netbeans GUI editor it makes it a little more complicated. I've set the Jtable as public static and the "table = new JTable(mTableModel);" as followed in the example. It still dont work.
    Any ideas?

  • Removing rows and inserting new rows with new data in JTAble!!! (Plz. help)

    I have a problem, The scenario is that when I click any folder that si in my JTable's first row, the table is update by removing all the rows and showing only the contents of my selected folder. Right now it's not removing the rows and instead throwing exceptions. The code is attached. The methods to look are upDateTabel(...) and clearTableData(....), after clearing all my rows then I proceed on adding my data to the Jtable and inserting rows but it's not being done. May be I have a problem in my DefaultTableModel class. Please see the code below what I am doing wrong and how should I do it. Any help is appreciated.
    Thanks
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import java.io.*;
    import java.text.SimpleDateFormat;
    import java.util.*;
    public class SimpleTable extends JPanel{
         /** Formats the date */
         protected SimpleDateFormat           formatter;
    /** variable to hold the date and time in a raw form for the directory*/
    protected long                          dateDirectory;
    /** holds the readable form converted date for the directories*/
    protected String                     dirDate;
    /** holds the readable form converted date for the files*/
    protected String                     fileDate;
    /** variable to hold the date and time in a raw form for the file*/
    protected long                          dateFile;
    /** holds the length of the file in bytes */
    protected long                         totalLen;
    /** convert the length to the wrapper class */
    protected Long                         longe;
    /** Vector to hold the sub directories */
    protected Vector                     subDir;
    /** holds the name of the selected directory */
    protected String                    dirNameHold;
    /** converting vector to an Array and store the values in this */
    protected File                     directoryArray[];
    /** hashtable to store the key-value pair */
    protected static Hashtable hashTable = new Hashtable();
    /** refer to the TableModel that is the default*/
    protected MyTableModel               tableModel;
    /** stores the path of the selected file */
    protected static String               fullPath;
    /** stores the currently selected file */
    protected static File selectedFilename;
    /** stores the extension of the selected file */
    protected static String           extension;
    protected int COLUMN_COUNT = 4;
         protected Vector data = new Vector( 0, 1 );
         protected final JTable table;
    /** holds the names of the columns */
    protected final String columnNames[] = {"Name", "Size", "Type", "Modified"};
    public SimpleTable(File directoryArray[])
              this.setLayout(new BorderLayout());
              this.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
              (SimpleTable.hashTable).clear();
              formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
              for(int k = 0; k < directoryArray.length; k++)
                   if(directoryArray[k].isDirectory())
                        dateDirectory = directoryArray[k].lastModified();
                        dirDate = formatter.format(new java.util.Date(dateDirectory));
                        data.addElement( new MyObj( directoryArray[k].getName(), "", "File Folder", "" + dirDate ) );
                        (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);                    
                   else if(directoryArray[k].isFile())
                        dateDirectory = directoryArray[k].lastModified();
                        fileDate = formatter.format(new java.util.Date(dateDirectory));
                        totalLen = directoryArray[k].length();
                        longe = new Long(totalLen);
                        data.addElement( new MyObj( directoryArray[k].getName(), longe + " Bytes", "", "" + fileDate ) );
                        (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
    tableModel = new MyTableModel();
              table = new JTable( tableModel );
              table.getTableHeader().setReorderingAllowed(false);
              table.setRowSelectionAllowed(false);
              table.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
              table.setShowHorizontalLines(false);
              table.setShowVerticalLines(false);
              table.addMouseListener(new MouseAdapter()
    public void mouseReleased(MouseEvent e)
         Object eventTarget = e.getSource();
                        if( eventTarget == table )
                             upDateTable(table);
                             table.tableChanged( new javax.swing.event.TableModelEvent(tableModel) ) ;
              DefaultTableCellRenderer D_headerRenderer = (DefaultTableCellRenderer ) table.getTableHeader().getDefaultRenderer();
              table.getColumnModel().getColumn(0).setHeaderRenderer(D_headerRenderer );
              ((DefaultTableCellRenderer)D_headerRenderer).setToolTipText("File and Folder in the Current Folder");
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    this.add(scrollPane, BorderLayout.CENTER);
    * Searches the Hashtable and returns the path of the folder or the value.
    public File findPath(String value)
         return (File)((SimpleTable.hashTable).get(value));
    * This clears the previous data in the JTable
    public void clearTableData(JTable table)
         for(int row = 0; row < table.getRowCount() ; row++)
                   //for (int col = 0; col < table.getColumnCount() ; col++)
                        tableModel.deleteSelections( row );
              tableModel.fireTableStructureChanged();
              tableModel.fireTableRowsDeleted(0,table.getRowCount());
              //table.getModel().fireTableChanged(new TableModelEvent(table.getModel()));
    private void upDateTable(JTable table)
    if((table.getSelectedColumn() == 0) && ((table.getColumnName(0)).equals(columnNames[0])))
         dirNameHold =(String) table.getValueAt(table.getSelectedRow(),table.getSelectedColumn());
                   File argument = findPath(dirNameHold);
                   if(argument.isFile())
                        CMRDialog.fileNameTextField.setText(argument.getName());
                        try
                             fullPath = argument.getCanonicalPath();                          
                             selectedFilename = argument.getCanonicalFile();                          
    CMRDialog.filtersComboBox.removeAllItems();
                             extension = fullPath.substring(fullPath.lastIndexOf('.'));
                             CMRDialog.filtersComboBox.addItem("( " + extension + " )" + " File");
                        catch(IOException e)
                             System.out.println("THE ERROR IS " + e);
                        return;
                   else if(argument.isDirectory())
                        String path = argument.getName();
                             //find the system dependent file separator
                             //String fileSeparator = System.getProperty("file.separator");
                        CMRDialog.driveComboBox.addItem(" " + path);
              subDir = Search.subDirs(argument);
              /**TBD:- needs a method to convert the vector to an array and return the array */
              directoryArray = new File[subDir.size()];
                   int indexCount = 0;
                   /** TBD:- This is inefficient way of converting a vector to an array */               
                   Iterator e = subDir.iterator();               
                   while( e.hasNext() )
                        directoryArray[indexCount] = (File)e.next();
                        indexCount++;
              /** now calls this method and clears the previous data */
              clearTableData(table);     
                   (SimpleTable.hashTable).clear();
                   //data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
                   formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
                   for(int k = 0; k < directoryArray.length; k++)
                        if(directoryArray[k].isDirectory())
                             dateDirectory = directoryArray[k].lastModified();
                             dirDate = formatter.format(new java.util.Date(dateDirectory));
                             data.addElement( new MyObj( directoryArray[k].getName(), "", "File Folder", "" + dirDate ) );
                             (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);                    
                        else if(directoryArray[k].isFile())
                             dateDirectory = directoryArray[k].lastModified();
                             fileDate = formatter.format(new java.util.Date(dateDirectory));
                             totalLen = directoryArray[k].length();
                             longe = new Long(totalLen);
                             data.addElement( new MyObj( directoryArray[k].getName(), longe + " Bytes", "", "" + fileDate ) );
                             (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
              // tableModel.fireTableDataChanged();          
              // tableModel.fireTableRowsInserted(0,1);
              table.revalidate();
              table.validate();               
    class MyTableModel extends DefaultTableModel
              int totalRows;
              int totalCols;
              public MyTableModel()
                   super();
                   setColumnIdentifiers (columnNames);
                   this.totalRows = data.size();
                   this.totalCols = columnNames.length;
              // this will return the row count of your table
              public int getRowCount()
                   return totalRows;
              // this return the column count of your table
              public int getColumnCount()
                   return totalCols;
              // this return the data for each cell in your table
              public Object getValueAt(int row, int col)
                   MyObj obj = (MyObj)data.elementAt( row );
                   if( obj != null )
                        if( col == 0 ) return( obj.first );
                        else if( col == 1 ) return( obj.last );
                        else if( col == 2 ) return( obj.third );
                        else if( col == 3 ) return( obj.fourth );
                        else return( "" );
                   return "";
              // if you want your table to be editable then return true
              public boolean isCellEditable(int row, int col)
                   return false;
              // if your table is editable edit the data vector here and
              // call table.tableChanged(...)
              public void setValueAt(Object value, int row, int col)
              protected void deleteSelections (int rows)
                   try
                        removeRow(rows);
                   catch(ArrayIndexOutOfBoundsException e)
                        System.out.println("The error in the row index " + rows);
                   fireTableDataChanged() ;
    class MyObj
              String first;
              String last;
              String third;
              String fourth;
              public MyObj( String f, String l, String t, String fo )
                   this.first = f;
                   this.last = l;
                   this.third = t;
                   this.fourth = fo;
    #####################################

    The following code works fine but it doesn't show me the new updated date in my JTable. I tried to print the values that I am getting and it does give the values on the prompt but doesn't show me on the JTable only first two are shown and the rest of the table is filled with the same values. I don't know what's going on and am tired of this TableModel thing so pla. take a time to give me some suggestions. Thanks
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import java.io.*;
    import java.text.SimpleDateFormat;
    import java.util.*;
    public class SimpleTable extends JPanel {
         /** Formats the date */
         protected SimpleDateFormat           formatter;
    /** two-dimensional array to hold the information for each column */
    protected Object                     data[][];
    /** variable to hold the date and time in a raw form for the directory*/
    protected long                          dateDirectory;
    /** holds the readable form converted date for the directories*/
    protected String                     dirDate;
    /** holds the readable form converted date for the files*/
    protected String                     fileDate;
    /** variable to hold the date and time in a raw form for the file*/
    protected long                          dateFile;
    /** holds the length of the file in bytes */
    protected long                         totalLen;
    /** convert the length to the wrapper class */
    protected Long                         longe;
    /** Vector to hold the sub directories */
    protected Vector                     subDir;
    /** holds the name of the selected directory */
    protected String                    dirNameHold;
    /** converting vector to an Array and store the values in this */
    protected File                     directoryArray[];
    /** hashtable to store the key-value pair */
    protected static Hashtable hashTable = new Hashtable();
    /** refer to the TableModel that is the default*/
    protected DefaultTableModel      model;
    /** stores the path of the selected file */
    protected static String               fullPath;
    /** stores the currently selected file */
    protected static File selectedFilename;
    /** stores the extension of the selected file */
    protected static String           extension;
    protected Vector                     m = new Vector(0,1);
    /** holds the names of the columns */
    protected final String columnNames[] = {"Name", "Size", "Type", "Modified"};
    public SimpleTable(File directoryArray[])
              this.setLayout(new BorderLayout());
              this.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
              (SimpleTable.hashTable).clear();
              data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
              formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
              for(int k = 0; k < directoryArray.length; k++)
                   if(directoryArray[k].isDirectory())
                        data[k][0] = directoryArray[k].getName();
                        data[k][2] = "File Folder";
                        dateDirectory = directoryArray[k].lastModified();
                        dirDate = formatter.format(new java.util.Date(dateDirectory));
                        data[k][3] = dirDate;
                        (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);                    
                   else if(directoryArray[k].isFile())
                        data[k][0] = directoryArray[k].getName();
                        totalLen = directoryArray[k].length();
                        longe = new Long(totalLen);
                        data[k][1] = longe + " Bytes";
                        dateFile = directoryArray[k].lastModified();
                        fileDate = formatter.format(new java.util.Date(dateFile));
                        data[k][3] = fileDate;
                        (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
    model = new DefaultTableModel();
    model.addTableModelListener( new TableModelListener(){
              public void tableChanged( javax.swing.event.TableModelEvent e )
                   System.out.println("************ I am inside the table changed method ********" );
              final JTable table = new JTable(model);
              table.getTableHeader().setReorderingAllowed(false);
              table.setRowSelectionAllowed(false);
              table.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
              table.setShowHorizontalLines(false);
              table.setShowVerticalLines(false);
              table.addMouseListener(new MouseAdapter()
    /* public void mousePressed(MouseEvent e)
    //System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
    /* if(e.getClickCount() >= 2 &&
    (table.getSelectedColumn() == 0) &&
    ((table.getColumnName(0)).equals(columnNames[0])))
         //System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
         upDateTable(table);
    public void mouseReleased(MouseEvent e)
    //System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
    /* if(e.getClickCount() >= 2 &&
    (table.getSelectedColumn() == 0) &&
    ((table.getColumnName(0)).equals(columnNames[0]))) */
         //System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
         upDateTable(table);
              /** set the columns */
              for(int c = 0; c < columnNames.length; c++)
                   model.addColumn(columnNames[c]);
              /** set the rows */
              for(int r = 0; r < data.length; r++)
                   model.addRow(data[r]);
              DefaultTableCellRenderer D_headerRenderer = (DefaultTableCellRenderer ) table.getTableHeader().getDefaultRenderer();
              table.getColumnModel().getColumn(0).setHeaderRenderer(D_headerRenderer );
              ((DefaultTableCellRenderer)D_headerRenderer).setToolTipText("File and Folder in the Current Folder");
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    this.add(scrollPane, BorderLayout.CENTER);
    * Returns the number of columns
    public int getColumnTotal()
         return columnNames.length;
    * Returns the number of rows
    public int getRowTotal(Object directoryArray[])
         return directoryArray.length;
    private void upDateTable(JTable table)
    if((table.getSelectedColumn() == 0) && ((table.getColumnName(0)).equals(columnNames[0])))
         dirNameHold =(String) table.getValueAt(table.getSelectedRow(),table.getSelectedColumn());
                   File argument = findPath(dirNameHold);
                   if(argument.isFile())
                        CMRDialog.fileNameTextField.setText(argument.getName());
                        try
                             fullPath = argument.getCanonicalPath();                          
                             selectedFilename = argument.getCanonicalFile();                          
    CMRDialog.filtersComboBox.removeAllItems();
                             extension = fullPath.substring(fullPath.lastIndexOf('.'));
                             CMRDialog.filtersComboBox.addItem("( " + extension + " )" + " File");
                        catch(IOException e)
                             System.out.println("THE ERROR IS " + e);
                        return;
                   else if(argument.isDirectory())
                        String path = argument.getName();
                             //find the system dependent file separator
                             //String fileSeparator = System.getProperty("file.separator");
                        CMRDialog.driveComboBox.addItem(" " + path);
              subDir = Search.subDirs(argument);
              /**TBD:- needs a method to convert the vector to an array and return the array */
              directoryArray = new File[subDir.size()];
                   int indexCount = 0;
                   /** TBD:- This is inefficient way of converting a vector to an array */               
                   Iterator e = subDir.iterator();               
                   while( e.hasNext() )
                        directoryArray[indexCount] = (File)e.next();
                        indexCount++;
              /** now calls this method and clears the previous data */
              clearTableData(table);     
                   (SimpleTable.hashTable).clear();
                   data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
                   formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
                   m.clear();
                   data = null;
                   data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
                   for(int k = 0; k < directoryArray.length; k++)
                        if(directoryArray[k].isDirectory())
                        System.out.println("Inside the if part");
                             data[k][0] = directoryArray[k].getName();
                             table.setValueAt(directoryArray[k].getName(),k,0);
                             //model.fireTableCellUpdated(k,0);
                             data[k][2] = "File Folder";
                             table.setValueAt("File Folder",k,2);
                             //model.fireTableCellUpdated(k,2);
                             dateDirectory = directoryArray[k].lastModified();
                             dirDate = formatter.format(new java.util.Date(dateDirectory));
                             data[k][3] = dirDate;
                             table.setValueAt(dirDate,k,3);
                             //model.fireTableCellUpdated(k,3);
                             (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
                             m.add(data);
                             model.addRow(m);
                             model.fireTableDataChanged();                              
                        else if(directoryArray[k].isFile())
                   System.out.println("******* Inside the else part *******");
                             data[k][0] = directoryArray[k].getName();
                   System.out.println("The Name is == " + data[k][0]);
                             table.setValueAt(directoryArray[k].getName(),k,0);
                   System.out.println("The table cell value of the name is == " + table.getValueAt(k,0));
                             //model.fireTableCellUpdated(k,0);
                             totalLen = directoryArray[k].length();
                             longe = new Long(totalLen);
                             data[k][1] = longe + " Bytes";
                   System.out.println("The length == " + data[k][1]);
                             table.setValueAt(longe + " Bytes",k,1);
                   System.out.println("The table cell value of the length is == " + table.getValueAt(k,1));
                             //model.fireTableCellUpdated(k,0);
                             dateFile = directoryArray[k].lastModified();
                             fileDate = formatter.format(new java.util.Date(dateFile));
                             data[k][3] = fileDate;
                   System.out.println("The modified date == " + data[k][3]);
                             table.setValueAt(fileDate,k,3);
                   System.out.println("The table cell value of the name is == " + table.getValueAt(k,3));
                             //model.fireTableCellUpdated(k,0);
                             (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);                    }
                             m.add(data);
                             model.addRow(m);
                             model.fireTableDataChanged();     
              // model.fireTableDataChanged();          
              // model.fireTableRowsInserted(0,1);
              table.revalidate();
              table.validate();               
         else
    * Searches the Hashtable and returns the path of the folder or the value.
    public File findPath(String value)
         return (File)((SimpleTable.hashTable).get(value));
    * This clears the previous data in the JTable
    public void clearTableData(JTable table)
         for(int row = 0; row < table.getRowCount() ; row++)
                   for (int col = 0; col < table.getColumnCount() ; col++)
                        table.setValueAt(null, row , col);
              model.fireTableStructureChanged();
    ###

  • Inserting one table records to the another table

    Hi There
    Though i don't close the Result set , My program throws the following Exception
    java.sql.SQLException: ResultSet is ClosedBecause of this my program Inserts only one record in the another table
    My code is this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.DefaultComboBoxModel.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    public class SearchBook extends JDialog implements ActionListener
         private JComboBox comboCategory,comboAuthor;
         private JSplitPane splitpane;
         private JTable table;
         private JToolBar toolBar;
         private JButton btnclose, btncancel;
         private JPanel panel1,panel2,panel3,panel4;
         private JLabel lblCategory,lblAuthor;
         private Container c;
         //DefaultTableModel model;
         Statement st;
         ResultSet rs;
         Vector v = new Vector();
         public SearchBook (Connection con)
              // Property for JDialog
              setTitle("Search Books");
              setLocation(40,110);
              setModal(true);
              setSize(750,450);
              // Creating ToolBar Button
              btnclose = new JButton(new ImageIcon("Images/export.gif"));
              btnclose.addActionListener(this);
              // Creating Tool Bar
              toolBar = new JToolBar();
              toolBar.add(btnclose);
              try
                   st=con.createStatement();
                   rs =st.executeQuery("SELECT BCat from Books Group By Books.BCat");
                   while(rs.next())
                        v.add(rs.getString(1));
              catch(SQLException ex)
                   System.out.println("Error");
              panel1= new JPanel();
              panel1.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
              lblCategory = new JLabel("Category:");
              lblCategory.setHorizontalAlignment (JTextField.CENTER);
              c.gridx=2;
              c.gridy=2;
              panel1.add(lblCategory,c);
              comboCategory = new JComboBox(v);
              comboCategory.addActionListener(this);
              c.ipadx=20;
              c.gridx=3;
              c.gridwidth=1;
              c.gridy=2;
              panel1.add(comboCategory,c);
              lblAuthor = new JLabel("Author/Publisher:");
              c.gridwidth=2;
              c.gridx=1;
              c.gridy=4;
              panel1.add(lblAuthor,c);
              lblAuthor.setHorizontalAlignment (JTextField.LEFT);
              comboAuthor = new JComboBox();
              comboAuthor.addActionListener(this);
              c.insets= new Insets(20,0,0,0);
              c.ipadx=20;
              c.gridx=3;
              c.gridy=4;
              panel1.add(comboAuthor,c);
              comboAuthor.setBounds (125, 165, 175, 25);
              table = new JTable();
              JScrollPane scrollpane = new JScrollPane(table);
              //panel2 = new JPanel();
              //panel2.add(scrollpane);
              splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,panel1,scrollpane);
              splitpane.setDividerSize(15);
              splitpane.setDividerLocation(190);
              getContentPane().add(toolBar,BorderLayout.NORTH);
              getContentPane().add(splitpane);
         public void actionPerformed(ActionEvent ae)
              Object obj= ae.getSource();
              if(obj==comboCategory)
                   String selecteditem = (String)comboCategory.getSelectedItem();
                   displayAuthor(selecteditem);
                   System.out.println("Selected Item"+selecteditem);
              else if(obj==btnclose)
                   dispose();     
              else if(obj==comboAuthor)
                   String selecteditem1 = (String)comboAuthor.getSelectedItem();
                   displayavailablity(selecteditem1);
                   //System.out.println("Selected Item"+selecteditem1);
                   System.out.println("Selected Author"+selecteditem1);
         private void displayAuthor(String selecteditem)
              try
              {     Vector data = new Vector();
                   rs= st.executeQuery("SELECT BAuthorandPublisher FROM Books where BCat='" + selecteditem + "' Group By Books.BAuthorandPublisher");
                   System.out.println("Executing");
                   while(rs.next())
                        data.add(rs.getString(1));
                   //((DefaultComboBoxModel)comboAuthor.getModel()).setVectorData(data);
                   comboAuthor.setModel(new DefaultComboBoxModel(data));
                   //rs.close();
              catch(SQLException ex)
                   System.out.println("ERROR");
         private void displayavailablity(String selecteditem1)
                   try
                        Vector columnNames = new Vector();
                        Vector data1 = new Vector();
                        String bname,bauthor,bcategory,bref1,bavail,bid;
                        int bref,mid,num;
                        rs = st.executeQuery("SELECT * FROM Books where BAuthorandPublisher='" + selecteditem1 +"'");     
                        while(rs.next())
                             bname = rs.getString("BName");                         
                             bauthor = rs.getString("BAuthorandPublisher");
                             bcategory = rs.getString("BCat");
                             bref = rs.getInt("BRef");
                             if(bref==1)bref1="Yes";
                             else bref1 = "No";
                             mid = rs.getInt("Mid");
                             if(mid==0)bavail="Available";
                             else bavail="Issued To:"+mid;
                             bid = rs.getString("BId");
                             System.out.println("Book Name is::"+bname);
                             System.out.println("Book Availabilty::"+bavail);
                             num = st.executeUpdate("insert into BSearch Values('"+bid+"','"+bname+"','"+bcategory+"','"+bauthor+"','"+bavail+"','"+bref1+",')");
                             System.out.println("Inseted in the table");
                        /**ResultSetMetaData md= rs.getMetaData();
                        int columns =md.getColumnCount();
                        String booktblheading[]={"Book ID","Book NAME","BOOK AUTHOR/PUBLISHER","REFRENCE","CATEGORY"};
                        for(int i=1; i<= booktblheading.length;i++)
                             columnNames.addElement(booktblheading[i-1]);
                        while(rs.next())
                             Vector row = new Vector(columns);
                             for(int i=1;i<=columns;i++)
                                  row.addElement(rs.getObject(i));
                             data1.addElement(row);
                             //System.out.println("data is:"+data);
                        ((DefaultTableModel)table.getModel()).setDataVector(data1,columnNames);
                        //DefaultTableModel model = new DefaultTableModel(data1,columnNames);
                        //table.setModel(model);
                        //rs.close();
                        //st.close(); */
                   catch(SQLException ex)
                        ex.printStackTrace();
    }Please help me Friends. I am very new to java. otherwise give me some suggestion to implement this idea in effective manner.
    Thank you for your service
    Cheers

    Hi
    Here i am Posting My programs code
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.DefaultComboBoxModel.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    public class SearchBook extends JDialog implements ActionListener
         private JComboBox comboCategory,comboAuthor;
         private JSplitPane splitpane;
         private JTable table;
         private JToolBar toolBar;
         private JButton btnclose, btncancel;
         private JPanel panel1,panel2,panel3,panel4;
         private JLabel lblCategory,lblAuthor;
         private Container c;
         //DefaultTableModel model;
         Statement st,st1;
         ResultSet rs,rs1,rs2;
         Vector v = new Vector();
         public SearchBook (Connection con)
              // Property for JDialog
              setTitle("Search Books");
              setLocation(40,110);
              setModal(true);
              setSize(750,450);
              // Creating ToolBar Button
              btnclose = new JButton(new ImageIcon("Images/export.gif"));
              btnclose.addActionListener(this);
              // Creating Tool Bar
              toolBar = new JToolBar();
              toolBar.add(btnclose);
              try
                   st=con.createStatement();
                   rs =st.executeQuery("SELECT BCat from Books Group By Books.BCat");
                   while(rs.next())
                        v.add(rs.getString(1));
              catch(SQLException ex)
                   System.out.println("Error");
              panel1= new JPanel();
              panel1.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
              lblCategory = new JLabel("Category:");
              lblCategory.setHorizontalAlignment (JTextField.CENTER);
              c.gridx=2;
              c.gridy=2;
              panel1.add(lblCategory,c);
              comboCategory = new JComboBox(v);
              comboCategory.addActionListener(this);
              c.ipadx=20;
              c.gridx=3;
              c.gridwidth=1;
              c.gridy=2;
              panel1.add(comboCategory,c);
              lblAuthor = new JLabel("Author/Publisher:");
              c.gridwidth=2;
              c.gridx=1;
              c.gridy=4;
              panel1.add(lblAuthor,c);
              lblAuthor.setHorizontalAlignment (JTextField.LEFT);
              comboAuthor = new JComboBox();
              comboAuthor.addActionListener(this);
              c.insets= new Insets(20,0,0,0);
              c.ipadx=20;
              c.gridx=3;
              c.gridy=4;
              panel1.add(comboAuthor,c);
              comboAuthor.setBounds (125, 165, 175, 25);
              table = new JTable();
              JScrollPane scrollpane = new JScrollPane(table);
              //panel2 = new JPanel();
              //panel2.add(scrollpane);
              splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,panel1,scrollpane);
              splitpane.setDividerSize(15);
              splitpane.setDividerLocation(190);
              getContentPane().add(toolBar,BorderLayout.NORTH);
              getContentPane().add(splitpane);
         public void actionPerformed(ActionEvent ae)
              Object obj= ae.getSource();
              if(obj==comboCategory)
                   String selecteditem = (String)comboCategory.getSelectedItem();
                   displayAuthor(selecteditem);
                   System.out.println("Selected Item"+selecteditem);
              else if(obj==btnclose)
                   dispose();     
              else if(obj==comboAuthor)
                   String selecteditem1 = (String)comboAuthor.getSelectedItem();
                   displayavailablity(selecteditem1);
                   //System.out.println("Selected Item"+selecteditem1);
                   System.out.println("Selected Author"+selecteditem1);
         private void displayAuthor(String selecteditem)
              try
              {     Vector data = new Vector();
                   rs1= st.executeQuery("SELECT BAuthorandPublisher FROM Books where BCat='" + selecteditem + "' Group By Books.BAuthorandPublisher");
                   System.out.println("Executing");
                   while(rs1.next())
                        data.add(rs1.getString(1));
                   //((DefaultComboBoxModel)comboAuthor.getModel()).setVectorData(data);
                   comboAuthor.setModel(new DefaultComboBoxModel(data));
              catch(SQLException ex)
                   System.out.println("ERROR");
         private void displayavailablity(String selecteditem1)
                   try
                        Vector columnNames = new Vector();
                        Vector data1 = new Vector();
                        String bname,bauthor,bcategory,bref1,bavail,bid;
                        int bref,mid,num;
                        //rs2.Open();
                        rs = st.executeQuery("SELECT * FROM Books where BAuthorandPublisher='" + selecteditem1 +"'");     
                        boolean tr=true;
                        while(rs.next())
                             if(true)
                                  bname = rs.getString("BName");                         
                                  bauthor = rs.getString("BAuthorandPublisher");
                                  bcategory = rs.getString("BCat");
                                  bref = rs.getInt("BRef");
                                  if(bref==1)bref1="Yes";
                                  else bref1 = "No";
                                  mid = rs.getInt("Mid");
                                  if(mid==0)bavail="Available";
                                  else bavail="Issued To:"+mid;
                                  bid = rs.getString("BId");
                                  System.out.println("Book Name is::"+bname);
                                  System.out.println("Book Availabilty::"+bavail);
                             num = st1.executeUpdate("insert into BSearch Values('"+bid+"','"+bname+"','"+bcategory+"','"+bauthor+"','"+bavail+"','"+bref1+",')");
                             System.out.println("Inseted in the table");
                   catch(SQLException ex)
                        ex.printStackTrace();
    }Thank you for your service

  • Using DefaultTableModel features

    I have my data model which I pass to AbstractTableModel and wrote my own implementation of getValueAt() method.
    I want to use the features provided by DefaultTableModel; for Eg addRows(), moveRows() rotate() etc.
    But defaultTableModel Treats Vector as its DataObject. In my case its different.
    What is the best way to use features of DefaultTableModel.
    TIA
    Zoha.

    What is the best way to use features of DefaultTableModel.Create a DefaultTableModel or extend the DefaultTableModel.
    If you are extending AbstractTableModel then you can't use the methods of DefaultTableModel, you have to write your own. Look at the DefaultTableModel source code for an idea of how to implement the methods. If you model doesn't use Vectors then you need to write your own routing to insert/remove rows of data from the TableModel.

  • JTable: HOW TO INSERT ROWS AND DATA?

    I have one JFrame on screen and inside of this i have a JTable, the question is how to insert rows and data into the JTable?

    [http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]
    In future, please post Swing questions to the [Swing Forum.|http://forums.sun.com/forum.jspa?forumID=57]
    In short, your TableModel is probably a DefaultTableModel . Study its API.

  • How to insert One table value to Another Table

    Hi friends
    Please have a look on this Code. Since i am new Java i am not able to findout the Solution for it
    private void displayavailablity(String selecteditem1)
                   try
                        Vector columnNames = new Vector();
                        Vector data1 = new Vector();
                        String bname,bauthor,bcategory,bref1,bavail,bid;
                        int bref,mid,num;
                        rs = st.executeQuery("SELECT * FROM Books where BAuthorandPublisher='" + selecteditem1 +"'");     
                        while(rs.next())
                             bname = rs.getString("BName");                         
                             bauthor = rs.getString("BAuthorandPublisher");
                             bcategory = rs.getString("BCat");
                             bref = rs.getInt("BRef");
                             if(bref==1)bref1="Yes";
                             else bref1 = "No";
                             mid = rs.getInt("Mid");
                             if(mid==0)bavail="Available";
                             else bavail="Issued To:"+mid;
                             bid = rs.getString("BId");
                             System.out.println("Book Name is::"+bname);
                             System.out.println("Book Availabilty::"+bavail);
                             num = st.executeUpdate("insert into BSearch Values('"+bid+"','"+bname+"','"+bcategory+"','"+bauthor+"','"+bavail+"','"+bref1+",')");
                             System.out.println("Inseted in the table");
                        /**ResultSetMetaData md= rs.getMetaData();
                        int columns =md.getColumnCount();
                        String booktblheading[]={"Book ID","Book NAME","BOOK AUTHOR/PUBLISHER","REFRENCE","CATEGORY"};
                        for(int i=1; i<= booktblheading.length;i++)
                             columnNames.addElement(booktblheading[i-1]);
                        while(rs.next())
                             Vector row = new Vector(columns);
                             for(int i=1;i<=columns;i++)
                                  row.addElement(rs.getObject(i));
                             data1.addElement(row);
                             //System.out.println("data is:"+data);
                        ((DefaultTableModel)table.getModel()).setDataVector(data1,columnNames);
                        //DefaultTableModel model = new DefaultTableModel(data1,columnNames);
                        //table.setModel(model);
                        rs.close();
                        //st.close(); */
                   catch(SQLException ex)
         }I trigger this Method when a JComboBox Item is Selected.
    For an example when i select an Item the select Query brings all the Record Equals to the Selected item. Now i want to insert the Selected items with some Modification to Another Table.
    Now the Problem is My Program Inserts Only One Record (Though there are Many Records Equals to Selected Item)
    Please give me a Better Solution
    Thank you

    jolif,
    If you're "new to java" then might I suggest you leave swing until you're "not so new to java"... it involves so many "advanced concepts" (unlike VB) that it constitutes a biohazard... i.e. it's fundamentally inimical to humanoid lifeforms.
    Now... Having duly vented my spleen, try rs.updateRow();

  • Inserting a column into JTable

    I can insert a column at the end, and then move it to the position i want it. When i have done this and print out the headers from the columns in the column model, then from index 0 up to (say) 6 are as i want them, with the new column at index 4.
    However, when i add a new column again, then the previously added column has an index of 6 and so isn't displayed in the position i want it.
    I'm using the moveColumn method as I have found people saying to use, it's just it doesn't seem to stick!
    Any ideas?

    Adding a new column to a DefaultTableModel fires a special TableModelEvent. Because of that the JTable reinitializes its TableColumnModel and any column movements are undone.
    You can call "setAutoCreateColumnsFromModel(false)" on the table but then you must update the TableColumnModel manually. The best solution is to build a table model with all necessary columns and to remove all TableColumn-Objekts from the TableColumnModel which should not be visible at first; adding TableColumn objects later wont alter the positions of the other columns.

Maybe you are looking for