Search code examples
javaswingjtablerowtablemodel

Java TableModel : Adding a row dynamically by clicking on the last row


So I am trying to implement a dynamically editable list and I want to add a row dynamically when I click on the last row or if I edit the last row. I know how to add the row although I would like to know how to implement the actionlistener. Help would be much appreciated.

 import java.awt.BorderLayout;
 import java.util.Date;

 import javax.swing.Icon;
 import javax.swing.ImageIcon;
 import javax.swing.JFrame;
 import javax.swing.JScrollPane;
 import javax.swing.JTable;
 import javax.swing.table.AbstractTableModel;
 import javax.swing.table.TableModel;

 public class EditListAction {
   public static void main(String args[]) {
     TableModel model = new AbstractTableModel() {
  Object rowData[] = {"English","hindi","Spanish","Russian" };

       String columnName = new String("Languages");

       public int getColumnCount() {
         return 1;
       }

       public String getColumnName() {
         return columnName;
       }

       public int getRowCount() {
         return rowData.length;
       }

       public Object getValueAt(int row,int col) {
         return rowData[row];
       }

       public Class getColumnClass(int column) {
         return (getValueAt(0, 1).getClass());
       }

       public void setValueAt(Object value, int row,int column) {
          if(column==0){
         rowData[row] = value;
          }
       }

       public boolean isCellEditable(int row, int column) {
         return (column == 0);
       }



     };

     JFrame frame = new JFrame("Column Renderer Table");
     JTable table = new JTable(model);
     JScrollPane scrollPane = new JScrollPane(table);
     frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
     frame.setSize(400, 150);
     frame.setVisible(true);
   }
 }

Solution

  • I know how to add the row

    Not based on the code you posted. Your custom TableModel uses a fixed size array to store the data. So you won't be able to add a new row unless you recreate the array every time which is not very efficient.

    Instead just use the DefaultTableModel. It already supports an addRow(...) method.

    If you want to add a row when clicking on the last row then add a MouseListener to the table. Then you can use the JTable's rowAtPoint(...) method to determine if the last row was clicked.

    If you want to add a row when the last row is edited then you can add a TableModelListener to the TableModel. You can then listen for updates to the last row.