Add/delete row in JTable

I went through the tutorial of JDK about how to programming JTable, i can NOT find a way to add/delete row into/from JTable.
I immagine it would be a difficult task because the data set it takes 'Object data[][]' is NOT dynamically grow/shrinkble.
Can we make it take ArrayList[] as input dataset so that the dataset can dynamically grow/shrink?
Any other way around to add/delete row?
THANKS for your consideration.

You have to write your own TableModel like extending AbstractTableModel. In that class add custom methods to add and remove rows. From those methods call fireTableRowsDeleted(..) and fireTableRowsInserted(..) to update UI.

Similar Messages

  • Problem in adding/deleting rows in JTable

    I am trying to add /remove rows from JTable whose first column is JButton and others are JComboBox's.If no rows are selected,new row is added at the end.If user selects some row & then presses insert button,new row is added below it.Rows can only be deleted if user has made some selection.Kindly help me,where i am making mistake.If any function is to be used.My code is as follows....
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    public class JButtonTableExample extends JFrame implements ActionListener{
    JComboBox mComboLHSType = new JComboBox();
    JComboBox mComboRHSType = new JComboBox();
    JLabel mLabelLHSType = new JLabel("LHS Type");
    JLabel mLabelRHSType = new JLabel("RHS Type");
    JButton mButtonDelete = new JButton("Delete");
    JButton mButtonInsert = new JButton("Insert");
    JPanel mPanelButton = new JPanel();
    JPanel mPanelScroll = new JPanel();
    JPanel mPanelCombo = new JPanel();
    DefaultTableModel dm ;
    JTable table;
    int currentRow = -1;
    static int mSelectedRow = -1;
    public JButtonTableExample()
    super( "JButtonTable Example" );
    makeForm();
    setSize( 410, 222 );
    setVisible(true);
    private void makeForm()
    this.getContentPane().setLayout(null);
    mPanelCombo.setLayout(null);
    mPanelCombo.setBorder(new LineBorder(Color.red));
    mPanelCombo.setBounds(new Rectangle(1,1,400,30));
    mLabelLHSType.setBounds(new Rectangle(26,5,71,22));
    mComboLHSType.setBounds(new Rectangle(83,5,100,22));
    mLabelRHSType.setBounds(new Rectangle(232,5,71,22));
    mComboRHSType.setBounds(new Rectangle(292,5,100,22));
    mPanelCombo.add(mLabelLHSType,null);
    mPanelCombo.add(mComboLHSType,null);
    mPanelCombo.add(mLabelRHSType,null);
    mPanelCombo.add(mComboRHSType,null);
    mPanelScroll.setLayout(null);
    mPanelScroll.setBorder(new LineBorder(Color.blue));
    mPanelScroll.setBounds(new Rectangle(1,28,400,135));
    mPanelButton.setLayout(null);
    mPanelButton.setBorder(new LineBorder(Color.green));
    mPanelButton.setBounds(new Rectangle(1,165,400,30));
    mButtonInsert.setBounds(new Rectangle(120,5,71,22));
    mButtonDelete.setBounds(new Rectangle(202,5,71,22));
    mButtonDelete.addActionListener(this);
    mButtonInsert.addActionListener(this);
    mPanelButton.add(mButtonDelete,null);
    mPanelButton.add(mButtonInsert,null);
    dm = new DefaultTableModel();
    //dm.setDataVector(null,
    //new Object[]{"Button","Join","LHS","Operator","RHS"});
    dm.setDataVector(new Object[][]{{"","","","",""}},
    new Object[]{"","Join","LHS","Operator","RHS"});
    table = new JTable(dm);
    table.getTableHeader().setReorderingAllowed(false);
    table.setRowHeight(25);
    int columnWidth[] = {20,45,95,95,95};
    TableColumnModel modelCol = table.getColumnModel();
    for (int i=0;i<5;i++)
    modelCol.getColumn(i).setPreferredWidth(columnWidth);
    //modelCol.getColumn(0).setCellRenderer(new ButtonRenderer());
    //modelCol.getColumn(0).setCellEditor(new ButtonEditor(new JCheckBox()));
    modelCol.getColumn(0).setCellRenderer(new ButtonCR());
    modelCol.getColumn(0).setCellEditor(new ButtonCE(new JCheckBox()));
    modelCol.getColumn(0).setResizable(false);
    setUpJoinColumn(modelCol.getColumn(1));
    setUpLHSColumn(modelCol.getColumn(2));
    setUpOperColumn(modelCol.getColumn(3));
    setUpRHSColumn(modelCol.getColumn(4));
    JScrollPane scroll = new JScrollPane(table);
    scroll.setBounds(new Rectangle(1,1,400,133));
    mPanelScroll.add(scroll,null);
    this.getContentPane().add(mPanelCombo,null);
    this.getContentPane().add(mPanelScroll,null);
    this.getContentPane().add(mPanelButton,null);
    }//end of makeForm()
    public void actionPerformed(ActionEvent ae)
    if (ae.getSource() == mButtonInsert)
    //int currentRow = table.getSelectedRow();
    currentRow = ButtonCE.selectedRow;
    System.out.println("Before Insert CURRENT ROW"+currentRow);
    if(currentRow == -1)
    int rowCount = dm.getRowCount();
    //mSelectedRow = rowCount-1;
    //table.clearSelection();
    dm.insertRow(rowCount,new Object[]{"","","","",""});
    currentRow = -1;
    ButtonCE.selectedRow = -1;
    else
    table.clearSelection();
    dm.insertRow(currentRow+1,new Object[]{"","","","",""});
    currentRow = -1;
    ButtonCE.selectedRow = -1;
    //System.out.println("After INSERT CURRENT ROW"+currentRow);
    if(ae.getSource() == mButtonDelete)
    //int currentRow = table.getSelectedRow();
    currentRow = ButtonCE.selectedRow;
    System.out.println("Before DELETE CURRENT ROW"+currentRow);
    if(currentRow != -1)
    dm.removeRow(currentRow);
    table.clearSelection();
    currentRow = -1;
    ButtonCE.selectedRow = -1;
    //System.out.println("Selected Row"+mSelectedRow);
    else
    JOptionPane.showMessageDialog(null, "Select row first", "alert", JOptionPane.ERROR_MESSAGE);
    //System.out.println("DELETE CURRENT ROW"+currentRow);
    public void setUpJoinColumn(TableColumn joinColumn)
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("AND");
    comboBox.addItem("OR");
    comboBox.addItem("NOT");
    joinColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    joinColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = joinColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    public void setUpLHSColumn(TableColumn LHSColumn)
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Participant1");
    comboBox.addItem("Participant2");
    comboBox.addItem("Variable1");
    LHSColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    LHSColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = LHSColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    public void setUpOperColumn(TableColumn operColumn)
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("=");
    comboBox.addItem("!=");
    comboBox.addItem("Contains");
    operColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    operColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = operColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    public void setUpRHSColumn(TableColumn rhsColumn)
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Variable1");
    comboBox.addItem("Constant1");
    comboBox.addItem("Constant2");
    rhsColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer =
    new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    rhsColumn.setCellRenderer(renderer);
    //Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = rhsColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the sport to see a list of choices");
    public static void main(String[] args) {
    JButtonTableExample frame = new JButtonTableExample();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    //Button as a renderer for the table cells
    class ButtonCR implements TableCellRenderer
    JButton btnSelect;
    public ButtonCR()
    btnSelect = new JButton();
    btnSelect.setMargin(new Insets(0,0,0,0));
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
    if (column != 0) return null; //meany !!!
    //System.out.println("Inside renderer########################Selected row");
    //btnSelect.setText(value.toString());
    //btnSelect.setIcon(new ImageIcon("capsigma.gif"));
    return btnSelect;
    }//end fo ButtonCR
    //Default Editor for table
    class ButtonCE extends DefaultCellEditor implements ActionListener
    JButton btnSelect;
    JTable table;
    //Object val;
    static int selectedRow = -1;
    public ButtonCE(JCheckBox whoCares)
    super(whoCares);
    //this.row = row;
    btnSelect = new JButton();
    btnSelect.setMargin(new Insets(0,0,0,0));
    btnSelect.addActionListener(this);
    setClickCountToStart(1);
    public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column)
    if (column != 0) return null; //meany !!!
    this.selectedRow = row;
    this.table = table;
    table.clearSelection();
    System.out.println("Inside getTableCellEditorComponent");
    return btnSelect;
    //public Object getCellEditorValue()
    //return val;
    public void actionPerformed(ActionEvent e)
    // Your Code Here...
    System.out.println("Inside actionPerformed");
    System.out.println("Action performed Row selected "+selectedRow);
    btnSelect.setIcon(new ImageIcon("capsigma.gif"));
    }//end of ButtonCE

    Hi,
    All the thing you have to do is to return a boolean for the column. JTable will use a checkbox (as default) to show boolean values.

  • My add/delete row function is unselectable. How do I fix this?

    For no reason that I can guess I am unable to add or delete rows. That little circle icon with the two horizontal dashes is gone and when I click on a numbered row the 'add/delete row' choices are grayed out, unelectable. My spreadsheet needs are VERY basic so I'm at a loss for what has happened because I've been using this file. It WAS working like it should, but now it's not and I don't know if I clicked something OFF or what. I am not new to a Mac, so I'm not a newbie with this stuff. Any ideas??????

    Try deactivating any filter you have set on the table.
    SG

  • How to add/delete rows on the form without saving data

    I am new to apex
    I am working on project and need some help on creating a form
    my requirment is to save a request that has multiple questions.
    i have a request form with multiple regions
    On one of the region that takes questions, I want to create a tabular form such that i can add/delete/update row without hitting database and enter multiple questions
    each row is one question.
    Apex has the default functionality of having a tabular form linked to a table that onload shows the data from that table and also on click of add or delete hits the data base to save the data.
    However i want to load a form that does not show any data if its a new request and click of add/delete should not update the databse. It should just add/delete a row on the form
    so user logs in and can create a request that has multiple questions
    finally want to submit the form and save all the information of the form in multiple tables.
    As of now i a m able to have a simple form and a process that save 1 question per request.
    How do i achieve this. Please assist.

    Do that using collections like in this example:
    http://apex.oracle.com/pls/otn/f?p=31517:176
    Once you are done, you may decide either to save that or to clean it up.
    Denes Kubicek
    http://deneskubicek.blogspot.com/
    http://www.opal-consulting.de/training
    http://apex.oracle.com/pls/otn/f?p=31517:1
    ------------------------------------------------------------------------------

  • Delete row in JTable

    Hello I am new To JAVA SWING
    I have 2 questions related to JTable
    1) How do i remove selected row in JTable ...for instance, I click on the row to delete (It is selected) , later I press the delete button, and then row is removed .... any hints ?
    2) If I would like to save the rows in a JTable into a database , .... How can iterate through the rows in the JTable..each row .... the rows are saved in a List object...and a List Object is what I pass as a parameter in a class method in order to be saved into Database.
    Thanks,
    deibys

    1) use the removeRow(...) method of the DefaultTableModel
    20 use table.getModel().getValueAt(...) to get the data from the model and create your list Object.

  • Editable ALV- Disable Add, delete row buttons

    Hi,
    I have an editable ALV using OO Grid. Some columns are editable and some are not using field catalog. I want to disable the 'add new row' and 'delete row' buttons. How to go about it ?
    Regards,
    Vin

    You can simply add them to the "Exclude" table and pass them to the SET_TABLE_FOR_FIRST_DISPLAY method.
       data: iexclude type ui_functions,
       data: xexclude type ui_func.
        define macro_exclude.
         xexclude = &1.
          append xexclude to iexclude.
        end-of-definition.
        macro_exclude cl_gui_alv_grid=>mc_fc_loc_copy_row.
        macro_exclude cl_gui_alv_grid=>mc_fc_loc_delete_row.
        macro_exclude cl_gui_alv_grid=>mc_fc_loc_append_row.
        macro_exclude cl_gui_alv_grid=>mc_fc_loc_insert_row.
        macro_exclude cl_gui_alv_grid=>mc_fc_loc_move_row.
        macro_exclude cl_gui_alv_grid=>mc_fc_loc_copy.
        macro_exclude cl_gui_alv_grid=>mc_fc_loc_cut.
        macro_exclude cl_gui_alv_grid=>mc_fc_loc_paste.
        macro_exclude cl_gui_alv_grid=>mc_fc_loc_paste_new_row.
        macro_exclude cl_gui_alv_grid=>mc_fc_loc_undo.
        call method alv_grid->set_table_for_first_display(
            exporting
                 it_toolbar_excluding  = iexclude     "<--- Right HEre
                 is_layout             = xlayout
            changing
                 it_outtab       =  izcmptrans[]
                 it_fieldcatalog = ifc[] ).
    Regards,
    Rich Heilman

  • BPM Object Presentation - array items - (add / delete rows dynamically)

    Hi,
    We have a BPM Object presentation which uses a 'group' inner object to display ROWS of data. The presentation has an 'array0' created by default to handle the 'group' of rows. It also has the '+' and '-' buttons by default.
    There is a field at the upper level which shows the 'sum' of values in individual rows. It needs to 'REFRESH' when an add (+) or deletetion (-) or rows happen.
    But we see that all the controls (text boxes etc which are wired to the 'inner' bpm object of the group and the +/- buttons are one unit 'array0'. And the only method if at all, is an 'Event Listner' which is not showing any methods related to BPM Object.
    Can anyone help us with a clue as to how to handle the '+' and '-' events or wire the 'array/group' events to code - any clue with 'events'?
    This is a little urgent as it is an issue and we need to fix the same. Appreciate any quick responses/clues.
    Thanks in advance,
    -user8702013.

    The SUM field needs refresh() method to be called to reflect the new value whenever we are adding/deleting rows.
    To call this method for to show the reflection we have to declare a method on BPM object level which receives a argument of type ‘Fuego.Util.GroupEvent’, then in this method you can have your logic(here refresh() method is required to show new value on deletion/addition, hence this method is being called). This method can then be wired (it shows up) to the 'Event Listener' of the group/array.
    The newly created method will be called whenever a new row is added/deleted (Event will be fired hence method call).

  • Add/remove rows in jTable

    Hello,
    I'm writing an application with Sun ONE Studio 4. The autogenerated code for a JTable is something like: jTable1.setModel(new javax.swing.table.DefaultTableModel...
    How can I add / remove rows from this table? In principle it should work like this: model.removeRow(0); But I don't have a model name in the autogenerated code.
    Thanks for your help, Elke

    DefaultTableModel model = (DefaultTableModel)<table>.getModel();
    model.doWhateverYouWant();
    Cheers,
    Ram

  • Add/Delete Rows problem

    I'm having a problem with the add row and delete row for my table.  I have a table set up with the add row button in the header, and the delete row button in the first cell of the row beneath the header.  I have it set so that the initial count of the row is 2.  My problem is if the user adds several rows with data, and save the form.  When that user goes back into the same form later, it keeps the several rows that the user entered, which is fine, but then it automatically adds 3 more blank rows to the table, which I don't want.  I don't understand why it is doing this.  Does anyone have a clue to why this is happening?
    Thanks
    Connie

    Hi Connie,
    Just make sure that you have checked the below thing.\
    File > Form Properties > Run tIme > Scripting > Automatically is checked.
    Thanks,
    Bibhu.

  • Add/Delete rows from ALV-grid

    Hi to all,
    i have 2 questions concerning alv-grids:
    i have an alvgrid displaying a table and what i need is some functionality to add or delete rows from the alvgrid - how can i do that ?
    within one row i have one field containing the status and i want to be able to select the status from a combo/dropdown-field and set it for this particular row.
    thanks in advance!

    Hi,
    Report BCALV_EDIT_04 shows how to append and delete rows.
    Report BCALV_EDIT_06 shows drop down list for cells in a column.
    These report should be available in any R/3 system including all ABAP Preview versions.
    Hope this can help.
    Regards, Johan

  • Add/Delete row

    Hello,
    How can add a new row directly after the current row not at the end of the form?
    For example: User fills the question/answer form and they want to add new row(s) to ones that already added. Suppose that they are at question 1, 2, 3 but realize that they want to add a new row between row#1 & 2 or row# 2 & 3 which can re-number to reflect the new row to the right number instead of at the end after row#3.
    Can any one please advise.
    Thanks,
    Han

    Hi Han,
    Check out this example: http://assure.ly/gk8Q7a.
    In particular Tables 5 (uses Tables) and 6 (uses Subforms). Basically I have set up the index cell as a button. When clicked it will "add" a new row directly underneath the row clicked.
    The script is in fact doing two things, one directly after the other.
    It adds a new row at the end of the table, and
    Then it moves that new row based on the index of that new instance.
    Does that make sense?
    Niall

  • Add/Delete rows in TableView

    hi all,
    i wanna add rows in the tableView and also wanna delete the selected rows from the tableView.
    how to do it?
    regards,
    purushothaman.

    Hi,
    As Harish said, use addElement to add elements to the Vector (using which you have created the DefaultTableViewModel and assigned it to your tableview).
    Capture the index of the rows to be deleted and use
    <Vector>.removeElementAt(index) to remove the specific rows.
    Check out this link as well
    http://help.sap.com/saphelp_nw04/helpdata/en/a9/76bd3b57743b09e10000000a11402f/frameset.htm
    http://java.sun.com/j2se/1.5.0/docs/api/
    Thanks
    Senthil
    P.S: Reward points for useful answers

  • Problem in deleting Rows of JTable after sorting it

    Hi all,
    I'm getting problems in Removing Row(s) after sorting a JTable.
    Please find the code snippets at this URL. Thanks for your time...
    http://forum.java.sun.com/thread.jsp?forum=31&thread=459736&start=15&range=15&hilite=false&q=

    Hi Abhijeet,
    I tried it the way you said using
         wdContext.nodeBirhtday_List().nodeItab().moveFirst();
         //     loop backwards to avoid index troubles
         for (int i = n - 1; i >= 0; --i)
              current_date  = wdContext.nodeBirhtday_List().nodeItab().currentItabElement().getGbdat().getDate();
              current_month = wdContext.nodeBirhtday_List().nodeItab().currentItabElement().getGbdat().getMonth();
              if (( current_date != date_today ) && ( current_month != month_today ))
                   wdContext.nodeBirhtday_List().nodeItab().removeElement(wdContext.nodeBirhtday_List().nodeItab().
                                  getElementAt(i));                
              wdContext.nodeBirhtday_List().nodeItab().moveNext();     
    It adds records...
    According to Valerys Solution, the IPrivate<CustomController> doesnt show me the required nodes. and gives me 'Unable to resolve' error.
    Can you please suggest where I am going wrong
    Regards
    Abdullah

  • Delete rows from JTable

    Hello
    I use a JTable with a custom table model that extends javax.swing.table.DefaultTableModel.
    I haven't overwrote the method
    public void removeRow(int row)Now when i use this method the rows always get removed from the end. It doesn't matter which value the parameter row has.
    Even when i call
    myTableModel.removeRow( 0 );it removes the rows at the end of the table.
    It would be nice if someone could help me with this.
    Regards, Michelle

    It's not so easy to do this because it's a big project, but here is the code of the table model.
    import javax.swing.table.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import java.util.*;
    public class AssignmentsTableModel2 extends DefaultTableModel implements TableModelListener
         static final long serialVersionUID = 41L;
         public AssignmentsTableModel2(String[][] arg1, String[] arg2)
              super(arg1, arg2);
         public Vector getColumnIdentifiers()
              return columnIdentifiers;
         @Override
         public int getColumnCount()
              return this.columnIdentifiers.size();
         @Override
         public int getRowCount()
              return this.dataVector.size();
         @Override
         public String getColumnName(int col)
            return (String)this.columnIdentifiers.elementAt( col );
         @Override
         public Object getValueAt(int rowIndex, int columnIndex)
              return ((Vector)this.dataVector.elementAt( rowIndex )).elementAt( columnIndex );
         @Override
         public void setValueAt( Object val, int rowIndex, int columnIndex )
              ((Vector)this.dataVector.elementAt( rowIndex )).set( columnIndex, val);
              fireTableCellUpdated( rowIndex, columnIndex );
         @Override
         public void tableChanged(TableModelEvent e)
         @Override
         public void setColumnIdentifiers(Vector columnIdentifiers)
              super.setColumnIdentifiers(columnIdentifiers);
         @Override
         public void removeRow(int row)
              this.dataVector.remove(row);
              System.out.println(row + " to remove");
              this.fireTableStructureChanged();
              //super.removeRow(row);
    }I need the model to change the background color of the cells at runtime and I now overwrote the removeRow() method, but it's still the same problem.
    Also I have a custom JTable class that colours the TableHeader of the selected column.
    class PaintedTable extends JTable {
        private static final long serialVersionUID = 1L;
        PaintedTable(AssignmentsTableModel2 atm)
            super(atm);
            setOpaque(false);
            ((JComponent) getDefaultRenderer(Object.class)).setOpaque(false);
        @Override
        public void paintComponent(Graphics g)
             //System.out.println("paint table");
            Color background = new Color(168, 210, 241);
            Color controlColor = new Color(230, 240, 230);
            int width = getWidth();
            int height = getHeight();
            Graphics2D g2 = (Graphics2D) g;
            Paint oldPaint = g2.getPaint();
            g2.setPaint(new GradientPaint(0, 0, background, width, 0, controlColor));
            g2.fillRect(0, 0, width, height);
            g2.setPaint(oldPaint);
            for (int row : getSelectedRows())
                Rectangle start = getCellRect(row, 0, true);
                Rectangle end = getCellRect(row, getColumnCount() - 1, true);
                g2.setPaint(new GradientPaint(start.x, 0, Color.orange, (int) ((end.x + end.width - start.x) * 1.25), 0, controlColor));
                g2.fillRect(start.x, start.y, end.x + end.width - start.x, start.height);
                //System.out.println("rect: (" + start.x + ", " + start.y + ") + (" + (end.x + end.width - start.x) + ", " + start.height +")");
            super.paintComponent(g);
        public boolean isCellEditable(int rowIndex, int colIndex)
            return false;  
    AssignmentsTableModel2 atm = new AssignmentsTableModel2(this.columnValues, this.columnHeaders);     
    PaintedTable table = new PaintedTable( this.atm );

  • Delete Multiple Rows of JTable by selecting JCheckboxes

    Hi,
    I want delete rows of JTable that i select through JCheckbox on clicking on JButton. The code that i am using is deleting one row at a time. I want to delete multiple rows at a time on clicking on Button.
    This is the code i m using
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableTest extends JFrame implements ActionListener
         JButton btnAdd;
         BorderLayout layout;
         DefaultTableModel model;
         JTable table;JButton btexcluir;
         public static void main(String[] args)
              TableTest app = new TableTest();
              app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TableTest()
              super("Table Example");
              btnAdd = new JButton("Add");
              btnAdd.addActionListener(this);
              model = new DefaultTableModel()
                   public Class getColumnClass(int col)
                        switch (col)
                             case 1 :
                                  return Boolean.class;
                             default :
                                  return Object.class;
              table = new JTable(model);
              table.setPreferredSize(new Dimension(250,200));
              // Create a couple of columns
              model.addColumn("Col1");
              model.addColumn("Col2");
              JCheckBox cbox = new JCheckBox();
              // Append a row
              JPanel painel = new JPanel();
              model.addRow(new Object[] { "v1",new Boolean(false)});
              model.addRow(new Object[] { "v3", new Boolean(false)});
              JScrollPane scrollPane = new JScrollPane(table);
              scrollPane.createVerticalScrollBar();
              btexcluir= new JButton("Excluir");
              btexcluir.addActionListener(this);
              painel.add(btexcluir);
              painel.add(btnAdd);
              getContentPane().add(scrollPane, BorderLayout.NORTH);
              getContentPane().add(painel, BorderLayout.SOUTH);
              setSize(600, 600);
              setVisible(true);
         public void actionPerformed(ActionEvent e)     {
           if (e.getSource() == btnAdd)     
              model.addRow(new Object[] { "Karl", new Boolean(false)});
           if (e.getSource()==btexcluir){
                for (int i=0; i <=model.getRowCount(); i++){
                     if (model.getValueAt(i,1)==Boolean.FALSE)
                          JOptionPane.showMessageDialog(null, "No lines to remove!!");
                     else if(model.getValueAt(i,1)==Boolean.TRUE)
                          model.removeRow(i);
    }Please reply me with code help.
    Thanks
    Nitin

    Hi,
    Thanks for ur support. My that problem is solved now. One more problem now . Initially i want that delete button disabled. When i select any checkbox that button should get enabled. how can i do that ?
    Thanks
    Nitin

Maybe you are looking for