Removing row and collumn in JTable

guys i have problem regarding JTable.. ive tried to search over the forum to find suitable answer but nothing fits in....
i need to refresh my JTable but i cant....
i've tried validate(), repaint() but it doesnt seem to work properly.
this is the portion of my code that generate the JTable
public void getTable()
          Statement statement;
          ResultSet resultSet;
          try
               String query = "SELECT * FROM Booking ";               statement = con.createStatement();
               resultSet = statement.executeQuery(query);
               displayResultSet(resultSet);
               statement.close();
          catch(SQLException sqle)
               sqle.printStackTrace();
     public void displayResultSet(ResultSet rs) throws SQLException
          boolean moreRecords = rs.next();
          if(!moreRecords)
               JOptionPane.showMessageDialog(this,"Data not found !","Information Message",JOptionPane.INFORMATION_MESSAGE);
               return;
          Vector columnHeads = new Vector();
          Vector rows = new Vector();
          try
               ResultSetMetaData rsmd = rs.getMetaData();
               for(int i = 1; i <= rsmd.getColumnCount(); ++i)
                    columnHeads.addElement(rsmd.getColumnName(i));
                    do
                         rows.addElement(getNextRow(rs,rsmd));
                    }while(rs.next());
                    table = new JTable(rows, columnHeads);
                    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                    table.setFont(new Font("Arial",Font.BOLD,10));
                    JScrollPane scroller = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                    gbConstraints.fill=GridBagConstraints.BOTH;
                    addComponent(scroller,4,1,4,4); // i use gridbaglayout
          catch(SQLException sqle){
               sqle.printStackTrace();
     public Vector getNextRow(ResultSet rs, ResultSetMetaData rsmd) throws SQLException
          Vector currentRow = new Vector();
          for(int i = 1; i <= rsmd.getColumnCount(); ++i)
          switch(rsmd.getColumnType(i))
               case Types.VARCHAR:
                    currentRow.addElement(rs.getString(i));
                    break;
               case Types.INTEGER:
                    currentRow.addElement(new Long(rs.getLong(i)));
                    break;
               default:
                    System.out.println("Type was: "+rsmd.getColumnTypeName(i));
          return currentRow;
when i pressed a button this method will execute again but will show the new updated query if it the database have allready been updated. i tried to validate and repaint but it doesnt work...
can some one out there tell me how to perform such task ?

ive tried to search over the forum to find suitable answerJTable is a Swing component and there is a forum for Swing questions. Maybe if you searched the Swing forum (and posted your question there) you would have had better results.
Here's an [url http://forum.java.sun.com/thread.jsp?forum=57&thread=504709]example (from the Swing forum) that shows how to repopulate a JTable by resetting the DataModel of the table with new data.

Similar Messages

  • 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();
    ###

  • How to freeze row and column in JTable

    Hi,
    I need to freeze first two rows and columns in a large JTable. I found ways to freeze either a row or a column, but not both at the same time.
    Can any of you help ?
    Found this code which allows freezing a col. Similar method can be used to freeze column
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JViewport;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableModel;
    public class FrozenTablePane extends JScrollPane{
    public FrozenTablePane(JTable table, int colsToFreeze){
    super(table);
    TableModel model = table.getModel();
    //create a frozen model
    TableModel frozenModel = new DefaultTableModel(
    model.getRowCount(),
    colsToFreeze);
    //populate the frozen model
    for (int i = 0; i < model.getRowCount(); i++) {
    for (int j = 0; j < colsToFreeze; j++) {
    String value = (String) model.getValueAt(i, j);
    frozenModel.setValueAt(value, i, j);
    //create frozen table
    JTable frozenTable = new JTable(frozenModel);
    //remove the frozen columns from the original table
    for (int j = 0; j < colsToFreeze; j++) {
    table.removeColumn(table.getColumnModel().getColumn(0));
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    //format the frozen table
    JTableHeader header = table.getTableHeader();
    frozenTable.setBackground(header.getBackground());
    frozenTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    frozenTable.setEnabled(false);
    //set frozen table as row header view
    JViewport viewport = new JViewport();
    viewport.setView(frozenTable);
    viewport.setPreferredSize(frozenTable.getPreferredSize());
    setRowHeaderView(viewport);
    setCorner(JScrollPane.UPPER_LEFT_CORNER, frozenTable.getTableHeader());
    }

    Hi,
    I need to freeze first two rows and columns in a large JTable. I found ways to freeze either a row or a column, but not both at the same time.
    Can any of you help ?
    Found this code which allows freezing a col. Similar method can be used to freeze column
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JViewport;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableModel;
    public class FrozenTablePane extends JScrollPane{
    public FrozenTablePane(JTable table, int colsToFreeze){
    super(table);
    TableModel model = table.getModel();
    //create a frozen model
    TableModel frozenModel = new DefaultTableModel(
    model.getRowCount(),
    colsToFreeze);
    //populate the frozen model
    for (int i = 0; i < model.getRowCount(); i++) {
    for (int j = 0; j < colsToFreeze; j++) {
    String value = (String) model.getValueAt(i, j);
    frozenModel.setValueAt(value, i, j);
    //create frozen table
    JTable frozenTable = new JTable(frozenModel);
    //remove the frozen columns from the original table
    for (int j = 0; j < colsToFreeze; j++) {
    table.removeColumn(table.getColumnModel().getColumn(0));
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    //format the frozen table
    JTableHeader header = table.getTableHeader();
    frozenTable.setBackground(header.getBackground());
    frozenTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    frozenTable.setEnabled(false);
    //set frozen table as row header view
    JViewport viewport = new JViewport();
    viewport.setView(frozenTable);
    viewport.setPreferredSize(frozenTable.getPreferredSize());
    setRowHeaderView(viewport);
    setCorner(JScrollPane.UPPER_LEFT_CORNER, frozenTable.getTableHeader());
    }

  • How to set the Selected row and Column in JTable

    Hi,
    i have a problem like the JTable having one Method getSelectedRow() and getSelectedColumn to know the Selected row and Column but if i want to explicitly set the Selected Row and Column,then there is no such type of Methods.If anybody has any solution then i will be thankful to him/her.
    Praveen K Saxena

    Is that what you're looking for? :myTable.getSelectionModel().setSelectionInterval(row, row);
    myTable.getColumnModel().getSelectionModel().setSelectionInterval(column, column);

  • How to add and remove rows and keep track of it

    hi all,
    i hv an issue
    im developing a page which will hv remove and add buttons for 3 categories
    on clicking it it should add r remove HTML table rows respective to which category button is pressed. and also i should track the number of rows added or deleted for a particular category.
    Is it possible with JSP
    a sample code wil also help me a lot
    thanks in advance

    i could not under how ur page structure is but i will try to tell what i used in such a situation where u have to add or remove some elements from the page based on wht the user chooses.
    I put buttons linking to the same page with a variable containing the row id in the url (http://something.com?id=10')
    while displaying the records i will be iterating througnh the data row by row and displaying the text in the table.
    but when i find a row id equal to the rowid passed i display it in another format with a form and text boxes to edit the data and a submit button to submit the data
    like...........
    while (rs.next())
         if(rs.getString("recid").trim().equalsIgnoreCase(request.getParameter("recid").trim()))
    %>
         <form name="form2" method="post" onsubmit="javascript:return ValidateForm(form2)" action="camp_update_msg_a.jsp">
         <tr class="colstyle3">
              <td width="5%" valign="middle"><%= rs.getString("questionno").trim() %></td><td><TEXTAREA NAME="question" COLS=35 ROWS=4 ><%= rs.getString("question").trim() %></TEXTAREA></td><td><TEXTAREA NAME="answer" COLS=15 ROWS=4 ><%= rs.getString("answerno").trim() %></TEXTAREA></td>
              <td><INPUT id="submit1" type="submit" value="Submit"></td><td><a href="camp_del_msg.jsp?campid=<%=request.getParameter(campid").trim() %">&recid=<%= rs.getString("recid") %>">Delete</a></td>
         </tr>
         </form>
    <%           }
    else
         { %>
         <tr class="colstyle3">
              <td width="5%" valign="middle"><%= rs.getString("questionno").trim() %></td><td><%= rs.getString("question").trim() %></td><td><%= rs.getString("answerno").trim() %></td>
              <td><a href="camp_edit_msg.jsp?campid=<%=request.getParameter("campid").trim() %>&recid=<%= rs.getString("recid") %>">Edit</a></td><td><a href="camp_del_msg.jsp?campid=<%=request.getParameter("campid").trim() %>&recid=<%= rs.getString("recid") %>">Delete</a></td>
         </tr>
    <%
    I think this information is helpful to u.......
    Good luck.............</a>

  • Problem removing rows from JTable

    Hello,
    I'm having an issue with a JTable that I'm using. At one point in my application, I want to remove all the rows from the table and regenerate them (from a database). When I try to remove the rows and do nothing else, they remain in the table. The rows are being removed from the model, as I have verified this in code, but the display does not refresh at all.
    I am using custom renderers to change the background color of a cell based on its value, and I disabled them to see if that was the problem, but alas, it is not.
    Any suggestions or ideas why this may be occurring?

    I am using model.setRowCount(0); to clear the model, however the display never refreshes. Then you are doing something wrong because its that simple. Only a single line of code is required.
    Perhaps I should have included this in my original post.Actually, you should have included demo code in your original post. That way we don't have to guess what you are doing.
    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.

  • JTable Problem (table does not show rows and columns)

    Hi All,
    What the table is suppose to do.
    - Load information from a database
    - put all the values in the first column
    - in the second column put combobox (cell editor with numbers 1-12)
    - the 3rd column put another combobox for something else
    - the 4th column uses checkbox as an edit
    The number of rows of the table should be equal to the number of
    record from
    the database. If not given it default to 20 (poor but ok for this)
    The number of columns is 4.
    But the table does not show any rows or
    column when I put it inside a
    JScrollPane (Otherwise it works).
    Please help,
    thanks in advance.
    public class SubjectTable extends JTable {
    * Comment for <code>serialVersionUID</code>
    private static final long serialVersionUID = 1L;
    /** combo for the list of classes */
    protected JComboBox classCombo;
    /** combo for the list of subjects */
    protected JComboBox subjectsCombo;
    /** combo for the list of grade */
    protected JComboBox gradeCombo;
    boolean canResize = false;
    boolean canReorder = false;
    boolean canSelectRow = false;
    boolean canSelectCell = true;
    boolean canSelectColumn = true;
    // the row height of the table
    int rowHeight = 22;
    // the height of the table
    int height = 200;
    // the width of the table
    int width = 300;
    // the size of the table
    Dimension size;
    * Parameterless constructor. Class the one of the other constructors
    to
    * create a table with the a new <code>SubjectTableModel</code>.
    public SubjectTable() {
    this(new SubjectTableModel());
    * Copy constructor to create the table with the given
    * <code>SubjectTableModel</code>
    * @param tableModel -
    * the <code>SubjectTableModel</code> with which to
    initialise
    * the table.
    SubjectTable(SubjectTableModel tableModel) {
    setModel(tableModel);
    setupTable();
    * Function to setup the table's functionality
    private void setupTable() {
    clear();
    // set the row hieght
    this.setRowHeight(this.rowHeight);
    // set the font size to 12
    //TODO this.setFont(Settings.getDefaultFont());
    // disble reordering of columns
    this.getTableHeader().setReorderingAllowed(this.canReorder);
    // disble resing of columns
    this.getTableHeader().setResizingAllowed(this.canResize);
    // enable the horizontal scrollbar
    this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    // disable row selection
    setRowSelectionAllowed(this.canSelectRow);
    // disable column selection
    setColumnSelectionAllowed(this.canSelectColumn);
    // enable cell selection
    setCellSelectionEnabled(this.canSelectCell);
    setPreferredScrollableViewportSize(getSize());
    TableColumn columns = null;
    int cols = getColumnCount();
    for (int col = 0; col < cols; col++) {
    columns = getColumnModel().getColumn(col);
    switch (col) {
    case 0:// subject name column
    columns.setPreferredWidth(130);
    break;
    case 1:// grade column
    columns.setPreferredWidth(60);
    break;
    case 2:// class room column
    columns.setPreferredWidth(120);
    break;
    case 3:// select column
    columns.setPreferredWidth(65);
    break;
    } // end switch
    }// end for
    // set up the cell editors
    doGradeColumn();
    doClassColumn();
    //doSubjectColumn();
    * Function to clear the table selection. This selection is different
    to
    * <code>javax.swing.JTable#clearSelection()</code>. It clears the
    user
    * input
    public void clear() {
    for (int row = 0; row < getRowCount(); row++) {
    for (int col = 0; col < getColumnCount(); col++) {
    if (getColumnName(getColumnCount() - 1).equals("Select")) {
    setValueAt(new Boolean(false), row, getColumnCount() - 1);
    }// if
    }// for col
    }// for row
    * Function to set the cell renderer for the subjects column. It uses
    a
    * combobox as a cell editor in the teacher's subjects table.
    public void doSubjectColumn() {
    TableColumn nameColumn = getColumnModel().getColumn(0);
    nameColumn.setCellEditor(new DefaultCellEditor(getSubjectsCombo()));
    // set up the celll renderer
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for drop down list");
    nameColumn.setCellRenderer(renderer);
    // Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = nameColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer) headerRenderer)
    .setToolTipText("Click the Name to see a list of choices");
    }// end doSubjectsColumn----------------------------------------------
    /** Function to set up the grade combo box. */
    public void doGradeColumn() {
    TableColumn gradeColumn = getColumnModel().getColumn(1);
    gradeColumn.setCellEditor(new DefaultCellEditor(getGradeCombo()));
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for drop down list");
    gradeColumn.setCellRenderer(renderer);
    // Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = gradeColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer) headerRenderer)
    .setToolTipText("Click the Grade to see a list of choices");
    }// end doGradeColumn-------------------------------------------------
    * Function to setup the Class room Column of the subjects
    public void doClassColumn() {
    // set the column for the classroom
    TableColumn classColumn = getColumnModel().getColumn(2);
    classColumn.setCellEditor(new DefaultCellEditor(getClassCombo()));
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for drop down list");
    classColumn.setCellRenderer(renderer);
    // Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = classColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer) headerRenderer)
    .setToolTipText("Click the Class to see a list of choices");
    }// end doClassColumn--------------------------------------------------
    * Function to get the size of the table
    * @return Returns the size.
    public Dimension getSize() {
    if (this.size == null) {
    this.size = new Dimension(this.height, this.width);
    return this.size;
    * Function to set the size of the table
    * @param dim
    * The size to set.
    public void setSize(Dimension dim) {
    if (dim != null) {
    this.size = dim;
    return;
    * Function to create/setup the class room comboBox. If the comboBox
    is
    * <code>null</code> a nwew one is created else the functon returns
    the
    * function that was returned initially.
    * @return Returns the classCombo.
    private JComboBox getClassCombo() {
    if (this.classCombo == null) {
    this.classCombo = new JComboBox();
    // fill up the class name combo
    ArrayList classRooms = new ArrayList();
    try {
    //TODO classRooms = Settings.getDatabase().getClassRooms();
    for (int i = 0; i < 10; i++) {
    String string = new String("Class");
    string += i;
    if (!classRooms.isEmpty()) {
    classRooms.trimToSize();
    for (int i = 0; i < classRooms.size(); i++) {
    this.classCombo.addItem(classRooms.get(i));
    } catch (Exception e) {
    e.printStackTrace();
    return this.classCombo;
    * Function to create/setup the subjects comboBox. If the comboBox is
    * <code>null</code> a nwew one is created else the functon returns
    the
    * function that was returned initially.
    * @return Returns the subjectsCombo.
    private JComboBox getSubjectsCombo() {
    if (this.subjectsCombo == null) {
    this.subjectsCombo = new JComboBox();
    try {
    ArrayList subjects = loadSubjectsFromDatabase();
    if (!subjects.isEmpty()) {
    Iterator iterator = subjects.iterator();
    while (iterator.hasNext()) {
    // create a new subject instance
    //TODO Subject subct = new Subject();
    // typecast to subject
    //TODO subct = (Subject) iterator.next();
    String name = (String) iterator.next();
    // add this subject to the comboBox
    //TODO this.subjectsCombo.addItem(subct.getName());
    subjectsCombo.addItem(name);
    }// end while
    }// end if
    else {
    JOptionPane.showMessageDialog(SubjectTable.this,
    "Subjects List Could Not Be Filled");
    System.out.println("Subjects List Could Not Be Filled");
    } catch (Exception e) {
    e.printStackTrace();
    return this.subjectsCombo;
    * Function to load subjects from the <code>Database</code>
    * @return Returns the subjects.
    private ArrayList loadSubjectsFromDatabase() {
    // list of all the subject that the school does
    ArrayList subjects = new ArrayList();
    try {
    //TODO to be removed later on
    for (int i = 0; i < 10; i++) {
    String string = new String("Subject");
    string += i;
    subjects.add(i, string);
    // set the school subjects
    //TODO subjects = Settings.getDatabase().loadAllSubjects();
    } catch (Exception e1) {
    e1.printStackTrace();
    return subjects;
    * Function to create/setup the grade comboBox. If the comboBox is
    * <code>null</code> a nwew one is created else the functon returns
    the
    * function that was returned initially.
    * @return Returns the gradeCombo.
    private JComboBox getGradeCombo() {
    if (this.gradeCombo == null) {
    this.gradeCombo = new JComboBox();
    // fill with grade 1 to 12
    for (int i = 12; i > 0; i--) {
    this.gradeCombo.addItem(new Integer(i).toString());
    return this.gradeCombo;
    public static void main(String[] args) {
    try {
    UIManager.setLookAndFeel(new Plastic3DLookAndFeel());
    System.out.println("Look and Feel has been set");
    } catch (UnsupportedLookAndFeelException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    SubjectTableModel model = new SubjectTableModel();
    int cols = model.getColumnCount();
    int rows = model.getRowCount();
    Object[][] subjects = new Object[rows][cols];
    for (int row = 0; row < rows; row++) {
    subjects[row][0] = new String("Subjectv ") + row;
    }//for
    model.setSubjectsList(subjects);
    SubjectTable ttest = new SubjectTable(model);
    JFrame frame = new JFrame("::Table Example");
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setViewportView(ttest);
    frame.getContentPane().add(scrollPane);
    frame.pack();
    frame.setVisible(true);
    **************************************END
    TABLE******************************
    ----------------------------THE TABLE
    MODEL----------------------------------
    * Created on 2005/03/21
    * SubjectTableModel
    package com.school.academic.ui;
    import javax.swing.table.AbstractTableModel;
    * Class extending the <code>AbstractTableModel</code> for use in
    creating the
    * <code>Subject</code>s table. In addition to the implemented methods
    of
    * <code>AbstractTableModel</code> The class creates a model that has
    initial
    * values - the values have their own <code>getter</code> and
    * <code>setter</code> methods - but can still be used for values that
    a user
    * chooses.
    * <p>
    * @author Khusta
    public class SubjectTableModel extends AbstractTableModel {
    * Comment for <code>serialVersionUID</code>
    private static final long serialVersionUID = 3257850978324461113L;
    /** Column names for the subjects table */
    String[] columnNames = { "Subject", "Grade", "Class Room",
    "Select" };
    /** Array of objects for the subjects table */
    Object[][] subjectsList;
    private int totalRows = 20;
    protected int notEditable = 0;
    * Parameterless constructor.
    public SubjectTableModel() {
    // TODO initialise the list
    // add column to the default table model
    this.subjectsList = new
    Object[getTotalRows()][getColumnNames().length];
    * Copy constructor with the <code>subjectList</code> to set
    * @param subjects
    public SubjectTableModel(Object[][] subjects) {
    this(0, null, subjects, 0);
    * Copy constructor with the initial number of row for the model
    * @param rows -
    * the initial rows of the model
    * @param cols -
    * the initial columns of the model
    * @param subjects -
    * the initial subjects for the model
    * @param edit - the minimum number of columns that must be
    uneditable
    public SubjectTableModel(int rows, String[] cols, Object[][]
    subjects, int edit) {
    // set the initial rows
    setTotalRows(rows);
    // set the column names
    setColumnNames(cols);
    // set the subjectlist
    setSubjectsList(subjects);
    //set not editable index
    setNotEditable(edit);
    * Function to get the total number of columns in the table
    * @return int -- the columns in the table
    public int getColumnCount() {
    if (this.subjectsList == null) {
    return 0;
    return getColumnNames().length;
    * Function to get the total number of rows in the table
    * @return int -- the rows in the table
    public int getRowCount() {
    if (this.subjectsList == null) {
    return 0;
    return this.subjectsList.length;
    * Function to get the name of a column in the table.
    * @param col --
    * the column to be named
    * @return String -- the column in the table
    public String getColumnName(int col) {
    if (getColumnNames()[col] != null) {
    return getColumnNames()[col];
    return new String("...");
    * Function to get the value of the given row.
    * @param row --
    * the row of the object.
    * @param col --
    * the col of the object.
    * @return Object -- the value at row, col.
    public Object getValueAt(int row, int col) {
    return getSubjectsList()[row][col];
    * Function to return the data type of the given column.
    * @param c --
    * the column whose type must be determined.
    * @return Class -- the type of the object in this col.
    public Class getColumnClass(int c) {
    if (getValueAt(0, c) != null) {
    return getValueAt(0, c).getClass();
    return new String().getClass();
    * Function to put a value into a table cell.
    * @param value --
    * the object that will be put.
    * @param row --
    * the row that the object will be put.
    * @param col --
    * the col that the object will be put.
    public void setValueAt(Object value, int row, int col) {
    * TODO: Have a boolean value to determine whether to clear or
    to set.
    * if true clear else set.
    if (value != null) {
    if (getSubjectsList()[0][col] instanceof Integer
    && !(value instanceof Integer)) {
    try {
    getSubjectsList()[row][col] = new
    Integer(value.toString());
    fireTableCellUpdated(row, col);
    } catch (NumberFormatException e) {
    * JOptionPane .showMessageDialog( this., "The \""
    +
    * getColumnName(col) + "\" column accepts only
    values
    * between 1 - 12");
    return;
    System.out.println("Value = " + value.toString());
    System.out.println("Column = " + col + " Row = " + row);
    // column = Grade or column = Select
    switch (col) {
    case 2:
    try {
    // TODO
    if (Boolean.getBoolean(value.toString()) == false
    && getValueAt(row, 0) != null
    && getValueAt(row, 1) != null
    && getValueAt(row, 2) != null) {
    // subjectsList[row][col + 1] = new
    Boolean(true);
    System.out.println("2. false - Updated...");
    * this.subjectListModel.add(row,
    * this.subjectsList[row][0] + new String(" -
    ") +
    * this.subjectsList[row][2]);
    } catch (ArrayIndexOutOfBoundsException exception) {
    exception.printStackTrace();
    break;
    case 3:
    if (Boolean.getBoolean(value.toString()) == false
    && getValueAt(row, 0) != null
    && getValueAt(row, 1) != null
    && getValueAt(row, 2) != null) {
    System.out.println("3. If - Added...");
    getSubjectsList()[row][3] = new Boolean(true);
    this.subjectListModel.addElement(this.subjectsList[row][0] +
    * new String(" - ") + this.subjectsList[row][2]);
    // subjectListModel.remove(row);
    fireTableCellUpdated(row, col);
    fireTableDataChanged();
    // this.doDeleteSubject();
    } else if (Boolean.getBoolean(value.toString()) ==
    true
    && getValueAt(row, 0) != null
    && getValueAt(row, 1) != null
    && getValueAt(row, 2) != null) {
    setValueAt("", row, col - 1);
    setValueAt("", row, col - 2);
    setValueAt("", row, col - 3);
    System.out.println("3. Else - Cleared...");
    // this.subjectListModel.remove(row);
    break;
    default:
    break;
    }// end switch
    getSubjectsList()[row][col] = value;
    fireTableCellUpdated(row, col);
    fireTableDataChanged();
    }// end if
    }// end
    * Function to enable edition for all the columns in the table
    * @param row --
    * the row that must be enabled.
    * @param col --
    * the col that must be enabled.
    * @return boolean -- indicate whether this cell is editble or
    not.
    public boolean isCellEditable(int row, int col) {
    if (row >= 0
    && (col >= 0 && col <= getNotEditable())) {
    return false;
    return true;
    * Function to get the column names for the model
    * @return Returns the columnNames.
    public String[] getColumnNames() {
    return this.columnNames;
    * Function to set the column names for the model
    * @param cols
    * The columnNames to set.
    public void setColumnNames(String[] cols) {
    // if the column names are null the default columns are used
    if (cols != null) {
    this.columnNames = cols;
    * Function to get the rows of subjects for the model
    * @return Returns the subjectsList.
    public Object[][] getSubjectsList() {
    if (this.subjectsList == null) {
    this.subjectsList = new
    Object[getTotalRows()][getColumnNames().length];
    return this.subjectsList;
    * Function to set the subjects list for the model
    * @param subjects
    * The subjectsList to set.
    public void setSubjectsList(Object[][] subjects) {
    // if the subject list is null create a new one
    // using default values
    if (subjects == null) {
    this.subjectsList = new
    Object[getTotalRows()][getColumnNames().length];
    return;
    this.subjectsList = subjects;
    * Function to get the total number of rows for the model. <b>NB:
    </b> This
    * is different to <code>
    getRowCount()</code>.<code>totalRows</code>
    * is the initial amount of rows that the model must have before
    data can be
    * added.
    * @return Returns the totalRows.
    * @see #setTotalRows(int)
    public int getTotalRows() {
    return this.totalRows;
    * Function to set the total rows for the model.
    * @param rows
    * The totalRows to set.
    * @see #getTotalRows()
    public void setTotalRows(int rows) {
    // if the rows are less than 0 the defaultRows are used
    // set getTotalRows
    if (rows > 0) {
    this.totalRows = rows;
    * Function to get the number of columns that is not editble
    * @return Returns the notEditable.
    public int getNotEditable() {
    return this.notEditable;
    * Function to set the number of columns that is not editable
    * @param notEdit The notEditable to set.
    public void setNotEditable(int notEdit) {
    if (notEdit < 0) {
    notEdit = 0;
    this.notEditable = notEdit;
    ----------------------------END TABLE MODEL----------------------------------

    I hope you don't expect us to read hundreds of lines of unformatted code? Use the "formatting tags" when you post.
    Why are you creating your own TableModel? It looks to me like the DefaultTableModel will store you data. Learn how to use JTable with its DefaultTableModel first. Then if you determine that DefaultTableModel doesn't provide the required functionality you can write your own model.

  • White patch after removing row from JTable

    I am working with JTable and removing item from table on clicking on button but after removing row there is white Patch on that row. I don�t want to show this white patch.
    I did repaint table but that is also not working.
    Any thoughts !!!!!!!

    javax.swing.SwingUtilities.invokeLater(new Runnable(){
                public void run(){
                  museTable.setBackground(Color.black);//your color here
              });

  • Removing Rows in JTable

    I Wrote an application to display the report of sales in JTable format and create a button "cancel" to remove all rows in the JTable.
    DefaultTableModel dtm=new DefaultTableModel();
    JTable t=new JTable(dtm);
    if(e.getSource()==cancel)
    int i=0;
    int rows=t.getRowCount();
    while(i<rows)
    dtm.removeRow(i);
    i++;
    When I click cancel,all rows are not removed.I have to click more than one time to cancel all the rows.kindly help me to remove all rows in the JTable in a single click.
    Thanks in advance.

    int i=0;
    int rows=t.getRowCount();
    while(i<rows)
    dtm.removeRow(i);
    i++;
    When I click cancel,all rows are not removed.I have to
    click more than one time to cancel all the rows.kindly
    help me to remove all rows in the JTable in a single
    click.Yeah, first you remove row0, and the previous row1 becomes row0, but you increase i, and remove the new row1 that is the previous row2, and so on. You should instead:
    int rows = dtm.getRowCount();
    while (--rows >= 0) {
    dtm.removeRow(rows);

  • JTable fixed Row and Column in the same window

    Hi
    Could anyone tip me how to make fixed row and column in the same table(s).
    I know how to make column fixed and row, tried to combine them but it didnt look pretty.
    Can anyone give me a tip?
    Thanks! :)

    Got it to work!
    heres the kod.. nothing beautiful, didnt clean it up.
    * NewClass.java
    * Created on den 29 november 2007, 12:51
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package tablevectortest;
    * @author Sockan
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class FixedRowCol extends JFrame {
      Object[][] data;
      Object[] column;
      JTable fixedTable,table,fixedColTable,fixedTopmodelTable;
      private int FIXED_NUM = 16;
      public FixedRowCol() {
        super( "Fixed Row Example" );
        data =  new Object[][]{
            {      "","A","A","A","",""},
            {      "a","b","","","",""},
            {      "a","","c","","",""},
            {      "","","","d","",""},
            {      "","","","","e",""},
            {      "","","","","","f"},
            {      "","b","","","",""},
            {      "","","c","","",""},
            {      "","","","d","",""},
            {      "","","","","e",""},
            {      "","b","","","",""},
            {      "","","c","","",""},
            {      "","","","d","",""},
            {      "","","","","e",""},
            {      "","","","","","f"},
            {      "I","","W","G","A",""}};
        column = new Object[]{"A","B","C","D","E","F"};
        AbstractTableModel fixedColModel = new AbstractTableModel() {
          public int getColumnCount() {
            return 1;
          public int getRowCount() {
            return data.length;
          public String getColumnName(int col) {
            return (String) column[col];
          public Object getValueAt(int row, int col) {
            return data[row][col];
          public boolean CellEditable(int row, int col) {
            return true;
        AbstractTableModel    model = new AbstractTableModel() {
          public int getColumnCount() { return column.length-2; }
          public int getRowCount() { return data.length - FIXED_NUM; }
          public String getColumnName(int col) {
           return (String)column[col+1];
          public Object getValueAt(int row, int col) {
            return data[row][col+1];
          public void setValueAt(Object obj, int row, int col) {
            data[row][col+1] = obj;
          public boolean CellEditable(int row, int col) {
            return true;
        AbstractTableModel fixedTopModel = new AbstractTableModel() {
          public int getColumnCount() { return 1; }
          public int getRowCount() { return data.length - FIXED_NUM; }
          public String getColumnName(int col) {
           return (String)column[col];
          public Object getValueAt(int row, int col) {
            return data[row][col];
          public void setValueAt(Object obj, int row, int col) {
            data[row][col] = obj;
          public boolean CellEditable(int row, int col) {
            return true;
        AbstractTableModel fixedModel = new AbstractTableModel() {     
          public int getColumnCount() { return column.length-2; }
          public int getRowCount() { return FIXED_NUM; }
          public Object getValueAt(int row, int col) {
            return data[row + (data.length - FIXED_NUM)][col+1];
        table = new JTable( model );
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fixedTable = new JTable( fixedModel );
        fixedTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fixedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fixedColTable= new JTable(fixedColModel);
        fixedColTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fixedColTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fixedTopmodelTable = new JTable(fixedTopModel);
        fixedTopmodelTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fixedTopmodelTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);   
        JScrollPane scroll      = new JScrollPane( table );
         scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
         scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        JScrollPane fixedScroll = new JScrollPane( fixedTable ) {
          public void setColumnHeaderView(Component view) {}
        fixedScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        fixedScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        JScrollBar bar = scroll.getVerticalScrollBar();
        JScrollBar dummyBar = new JScrollBar() {
          public void paint(Graphics g) {}
        dummyBar.setPreferredSize(bar.getPreferredSize());
        scroll.setVerticalScrollBar(dummyBar);
        final JScrollBar bar1 = scroll.getHorizontalScrollBar();
        JScrollBar bar2 = fixedScroll.getHorizontalScrollBar();
        bar2.addAdjustmentListener(new AdjustmentListener() {
          public void adjustmentValueChanged(AdjustmentEvent e) {
            bar1.setValue(e.getValue());
        JViewport viewport = new JViewport();
        viewport.setView(fixedColTable);
        viewport.setPreferredSize(fixedColTable.getPreferredSize());
        fixedScroll.setRowHeaderView(viewport);
        fixedScroll.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedColTable
            .getTableHeader());   
        JViewport viewport2 = new JViewport();
        viewport2.setView(fixedTopmodelTable);
        viewport2.setPreferredSize(fixedTopmodelTable.getPreferredSize());
        scroll.setRowHeaderView(viewport2);
        scroll.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedTopmodelTable
            .getTableHeader()); 
        scroll.setPreferredSize(new Dimension(600, 19));
        fixedScroll.setPreferredSize(new Dimension(600, 100)); 
        getContentPane().add(     scroll, BorderLayout.NORTH);
        getContentPane().add(fixedScroll, BorderLayout.CENTER);   
      public static void main(String[] args) {
        FixedRowCol frame = new FixedRowCol();
        frame.addWindowListener( new WindowAdapter() {
          public void windowClosing( WindowEvent e ) {
            System.exit(0);
        frame.pack();
        frame.setVisible(true);
    }

  • UDO: Add and Remove rows to/from Matrix.

    Hi all,
    Yes, I know there are lots of topics about adding and removing rows but I was having trouble with these and I need some expert's opinion.
    I'm working with a Document type UDO, with 1 header table (ADAT_ONR) and 1 child table (ADAT_NR1 -  MatrixUID = "mtx_NR").
    I add the first row when the user chooses the business partner.
    If oMatrix.RowCount = 0 Then
         oMatrix.AddRow()
          oMatrix.AutoResizeColumns()
         oMatrix.Columns.Item("V_LineId").Cells.Item(1).Specific.Value = 1
    End If
    Then, the user has to press the AddRow button to add new rows, and the user can only add 1 new blank row. Later I'll change the row adding behavior to mimic B1s.
                If pVal.BeforeAction = False Then
                    Select Case pVal.ItemUID
                        Case "AddRow"
                            'ItemHandler_Click = AddRow(oCompany, oApplication, oForm, oForm.Items.Item("mtx_NR").Specific.RowCount())
                            oMatrix = oForm.Items.Item("mtx_NR").Specific
                            If oMatrix.RowCount > 0 Then
                                If Trim(oMatrix.Columns.Item("V_PltCode").Cells.Item(oMatrix.RowCount).Specific.Value) = "" Then
                                    oApplication.StatusBar.SetText(TranslateStr(oApplication, MustChoosePallet), BoMessageTime.bmt_Short)
                                    Exit Function
                                End If
                            End If
                            ItemHandler_Click = NewLine(oCompany, oApplication, oForm)
                            Exit Function
        Private Function NewLine(ByRef oCompany As SAPbobsCOM.Company, ByRef oApplication As SAPbouiCOM.Application, _
            ByRef oForm As SAPbouiCOM.Form) As Boolean
            NewLine = False
            Try
                oMatrix = oForm.Items.Item("mtx_NR").Specific
                Dim Index As Integer = oMatrix.RowCount
                With oForm.DataSources.DBDataSources.Item("@ADAT_NR1")
                    .Clear()
                End With
                oMatrix.AddRow()
                oMatrix.Columns.Item("V_LineId").Cells.Item(Index + 1).Specific.Value = (Index + 1).ToString
                oMatrix.FlushToDataSource()
                oMatrix.LoadFromDataSource()
                oForm.Refresh()
                NewLine = True
            Catch ex As Exception
                oApplication.MessageBox("NewLine(): " & oCompany.GetLastErrorCode.ToString & ", " & ex.Message)
            End Try
        End Function
    When I Add or Update the data, I clear the last blank row, if it exists.
               '// In the Click Event
               If pVal.BeforeAction = True Then
                    Select Case pVal.ItemUID
                        Case "1"
                            If oForm.Mode <> BoFormMode.fm_FIND_MODE Then
                                oMatrix = oForm.Items.Item("mtx_NR").Specific
                                oMatrix.FlushToDataSource()
                                oMatrix.LoadFromDataSource()
                                If Trim(oMatrix.Columns.Item("V_PltCode").Cells.Item(oMatrix.RowCount).Specific.Value) = "" Then
                                    oForm.DataSources.DBDataSources.Item("@ADAT_NR1").RemoveRecord(oMatrix.RowCount - 1)
                                    oMatrix.DeleteRow(oMatrix.RowCount)
                                    'oMatrix.FlushToDataSource()
                                End If
                            End If
                    End Select
    My question is, Is there an easier way to Add and Delete Rows??
    BTW, I still have a problem so solve. With this code, when the user deletes a row the row numbering is incorrect. Example: if I have to rows in a matrix and I delete row nº1, row nº2 will hold the same number...
    Any Ideas?
    Thanks in advanced,
    Vítor Vieira

    Hi Victor,
    there is a Form Data event which you ca use in that try to write the code for adding a row after updating and delete a row while inserting and add a row while traversing.
    sample code.
    Sub FormDataEvent(ByRef BusinessObjectInfo As SAPbouiCOM.BusinessObjectInfo, ByRef BubbleEvent As Boolean)
            Try
                Select Case BusinessObjectInfo.EventType
                    Case SAPbouiCOM.BoEventTypes.et_FORM_DATA_ADD, SAPbouiCOM.BoEventTypes.et_FORM_DATA_UPDATE
                        If BusinessObjectInfo.BeforeAction = True Then
                            objForm = objMain.objApplication.Forms.Item(BusinessObjectInfo.FormUID)
                            oDBs_Head = objForm.DataSources.DBDataSources.Item("@Header")
                            oDBs_Detail= objForm.DataSources.DBDataSources.Item("@Line")
                            objMatrix = objForm.Items.Item("83").Specific
                            If objMatrix.VisualRowCount <> 0 Then
                                objMatrix.DeleteRow(objMatrix.VisualRowCount)
                                objMatrix.FlushToDataSource()
                            End If
                            If BusinessObjectInfo.EventType = SAPbouiCOM.BoEventTypes.et_FORM_DATA_ADD Then
                                End If
                        ElseIf BusinessObjectInfo.ActionSuccess = True Then
                            objForm = objMain.objApplication.Forms.Item(BusinessObjectInfo.FormUID)
                            If BusinessObjectInfo.EventType =                    SAPbouiCOM.BoEventTypes.et_FORM_DATA_UPDATE Then
                                objMatrix = objForm.Items.Item("83").Specific
                                objMatrix.AddRow()
                                SetNewLineCharge(objForm.UniqueID, objMatrix.VisualRowCount)
                                objMatrix.FlushToDataSource()
                              End If
                        End If
                    Case SAPbouiCOM.BoEventTypes.et_FORM_DATA_LOAD
                        If BusinessObjectInfo.ActionSuccess = True Then
                            oDBs_Head = objForm.DataSources.DBDataSources.Item("@Header")
                           oDBs_Detail = objForm.DataSources.DBDataSources.Item("@Line")
                            objMatrix = objForm.Items.Item("83").Specific
                            objMatrix.AddRow()
                            SetNewLineCharge(objForm.UniqueID, objMatrix.VisualRowCount)
                            objMatrix.FlushToDataSource()
                           End If
                End Select
                End Sub
    Hope this helps,
    OM Prakash

  • ADOBE Forms Central - add and remove rows (PDF Form)

    Hello, I am currently evaluating ‘ADOBE Forms Central' to set up a form with editable fields. I have set up a test form in ADOBE Forms Central and was unable to insert an option to add and remove rows similar to the print screen attached. Is this possible to do using ADOBE Forms Central or should I be using
    a different ADOBE application? Thank you, Liz

    A dynamic XFA PDF form can do this. You can create such forms with LiveCycle Designer, which was included with the Windows version of Acrobat Pro prior to version 11. It is now a separate product.
    XFA forms can't be used with FormsCentral, however, only Acroforms can.

  • Table with add and remove row function

    i want to have table that function like exactly like email table in yahoo or hotmail or any. the last column will have the checkbox an there is a button that reside on the top of the table that is used to delete all the checked data. i have tried to use AbstractTableModel with the data of type object[] but i don't know how to make the addRow and removeRow. can anyone help me i'm stuck!
    [Delete all check data] <-- jButton
    names | contact no | email | delete |
    john | 0000000000 | [email protected] | [] <-- checkbox
    tom | 0000000000 | [email protected] | [] <-- checkbox

    Is this really difficult ???
    Just use DefaultTableModel, use addRow method for add row, and use removeRow method to remove a row.
    Just loop your all table rows, get value at first column like:
    for( int i = 0; i < tableModel.getRowCount(); i++ ){
        //i assume you have checkbox in first columun of your table
        Boolean isSelected = ( Boolean )tableModel.getValueAt( i, 0 );
        if( isSelected.booleanValue() ){
            tableModel.removeRow( i );
    }

  • Remove specific row and column from 2d array

    Hi,
    I would like to know how to remove the specific row and column from 2d array.
    for example, I have the original 4x4 array as below
    2 -1 -1 0
    -1 2 0 -1
    -1 -1 2 0
    -1 -1 -1 3
    let say that i want to remove row 2(bold) and column 2(bold), and the new 2d array should get as below
    2 -1 0
    -1 2 -1
    -1 -1 3
    Thanks.

    You can't remove elements of an array, it's fixed at a certain size once created. What you can do however is make a new array and only copy the things you want. Something like:public static void main(String[] args) {
        Integer[][] bar = new Integer[5][5];
        for (int i = 0; i < bar.length; i++) {
            Integer[] baz = bar;
    Arrays.fill(baz, i);
    System.out.println(Arrays.toString(baz));
    Integer[][] muu = new Integer[5][4];
    removeColumn(3, bar, muu);
    for (Integer[] mee : muu) {
    System.out.println(Arrays.toString(mee));
    Integer[][] smuu = new Integer[4][5];
    removeRow(3, bar, smuu);
    for (Integer[] mee : smuu) {
    System.out.println(Arrays.toString(mee));
    public static <T> void removeRow(int row, T[][] a, T[][] result) {
    if (row >= a.length) {
    throw new IllegalArgumentException("no row at " + row);
    for (int a_r = 0, result_r = 0; a_r < a.length; a_r++) {
    if (a_r == row) {
    continue;
    System.arraycopy(a[a_r], 0, result[result_r], 0, a[a_r].length);
    result_r++;
    public static <T> void removeColumn(int col, T[][] a, T[][] result) {
    for (int i = 0; i < a.length; i++) {
    if (col >= a[i].length) {
    throw new IllegalArgumentException("no column at [" + i + ", " + col + "]");
    for (int a_i = 0, r_i = 0; a_i < a[i].length; a_i++) {
    if (a_i == col) {
    continue;
    result[i][r_i] = a[i][a_i];
    r_i++;

  • Select row and column from header in jtable

    hello i have a problem to select row and column from header in jtable..
    can somebody give me an idea on how to write the program on it.

    Hi Vicky Liu,
    Thank you for your reply. I'm sorry for not clear question.
    Answer for your question:
    1. First value of Open is item fiels in Dataset2 and this value only for first month (january). But for other month Open value get from Close in previous month.
    * I have 2 Dataset , Dataset1 is all data for show in my report. Dataset2 is only first Open for first month
    2. the picture for detail of my report
    Detail for Red number:
    1. tb_Open -> tb_Close in previous month but first month from item field in Dataset2
    espression =FormatNumber(Code.GetOpening(Fields!month.Value,First(Fields!open.Value, "Dataset2")))
    2. tb_TOTAL1 group on item_part = 1
    expression =FormatNumber(Sum(CDbl(Fields!budget.Value)))
    3. tb_TOTAL2 group on item_part = 3 or item_part = 4
    expression =FormatNumber(Sum(CDbl(Fields!budget.Value)) + ReportItems!tb_TOTAL1.Value )
    4. tb_TOTAL3 group on item_part = 2
    expression =FormatNumber(Sum(CDbl(Fields!budget.Value)) - ReportItems!tb_TOTAL2 .Value)
    5. tb_Close -> calculate from tb_TOTAL3 - tb_Open
    expression =FormatNumber(Code.GetClosing(ReportItems!tb_TOTAL3.Value,ReportItems!tb_Open.Value))
    I want to calculate the value of tb_Open and tb_Close. I try to use custom code for calculate them. tb_close is correct but tb_Open is not correct that show value = 0 .
    My custom code:
    Dim Shared prev_close As Double
    Dim Shared now_close As Double
    Dim Shared now_open As Double
    Public Function GetClosing(TOTAL3 as Double,NowOpening as Double)
        now_close = TOTAL3 + NowOpening
        prev_close = now_close
        Return now_close
    End Function
    Public Function GetOpening(Month as String,NowOpen as Double)
        If Month = "1" Then
            now_open = NowOpen
        Else    
            now_open = prev_close
        End If
        Return now_open
    End Function
    Thanks alot for your help!
    Regards
    Panda A

Maybe you are looking for