0

I'm working on jTable and I intend on deleting specific rows as part of the data manipulation to be conducted on the table. Essentially I've been able to successfully delete a row which the user would specify but I what I really want to do is to delete several rows based on boolean states or check boxes that are selected as part one of the four columns of the table.

I've attached a screenshot as to the current result of running the code and would like to be able to delete the rows based on the selected boolean states or check boxes.

Below is my code including my table model code which extends the AbstractTableModel:

package com.TableRowSelectProgramatically;

import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

@SuppressWarnings("serial")
public class JTableRowSelectProgramatically extends JPanel {

    public MyTableModel MyTableModel;

    public String Cell1 = "ABCD";

    public JTableRowSelectProgramatically() {
        initializePanel();
    }

    private void initializePanel() {

        setLayout(null);
        setPreferredSize(new Dimension(1250, 700));

        // Table model
        MyTableModel = new MyTableModel();

        // Table
        final JTable table = new JTable(MyTableModel);
        table.setFillsViewportHeight(true);

        // Row data
        Object[] values = {Cell1, "EFGH", "IJKL", new Boolean(false)};
        Object[] values2 = {"UVWX","QRST","MNOP", new Boolean(false)};
        Object[] values3 = {"ABCD","YZAB","CDEF", new Boolean(false)};
        final Object[] values4 = {"QWERTY","YTREWQ","QWERTY", new Boolean(false)};

        // Insert row data
        MyTableModel CustomTableModel = (MyTableModel) table.getModel();
        CustomTableModel.insertData(values);
        CustomTableModel.insertData(values2);
        CustomTableModel.insertData(values3);
        CustomTableModel.insertData(values);
        CustomTableModel.insertData(values2);
        CustomTableModel.insertData(values3);
        CustomTableModel.insertData(values);
        CustomTableModel.insertData(values2);
        CustomTableModel.insertData(values3);

        // Create edit menu label
        JLabel labelEditMenu = new JLabel("EDIT MENU:\n");

        // Create add row btn
        JButton addRow = new JButton("Add Row");

        // Attach listener for add row btn
        addRow.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                MyTableModel.insertData(values4);
            }
        });

        // Create delete row btn
        JButton deleteRow = new JButton("Delete Row");

        // Attach listener for delete btn
        deleteRow.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                MyTableModel.removeRow(1);
            }
        });

        // Create scroll pane
        JScrollPane pane = new JScrollPane(table);
        pane.setBounds(30, 30, 500, 500);

        // 
        JTextField AgentIDTextField = new JTextField();

        // Populate the JPanel
        JPanel dataEntryPanel = new JPanel(new FlowLayout());
        //dataEntryPanel.setBackground(Color.orange);
        dataEntryPanel.setBounds(540, 30, 500, 50);
        //dataEntryPanel.add(AgentIDTextField);
        dataEntryPanel.add(labelEditMenu);
        dataEntryPanel.add(addRow);
        dataEntryPanel.add(deleteRow);

        // Join up GUI
        add(pane);
        add(dataEntryPanel);
    }

    // Enable visibity of frame
    public static void showFrame() {
        JPanel panel = new JTableRowSelectProgramatically();

        JFrame frame = new JFrame("Test table");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    // Launch prog
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JTableRowSelectProgramatically.showFrame();
            }
        });
    }

    // Create custom table model for data entry
    class MyTableModel extends AbstractTableModel {

         private String[] columnNames = {"COLUMN 0", "COLUMN 1", "COLUMN 2", "COLUMN 3"};
         private Vector data = new Vector();

         @Override
         public int getRowCount() {
            return data.size();
         }

         @Override
         public int getColumnCount() {
             return columnNames.length;
         }

         @SuppressWarnings("rawtypes")
        @Override
         public Object getValueAt(int row, int col) {
             return ((Vector) data.get(row)).get(col);
         }

         public String getColumnName(int col){
             return columnNames[col];
         }

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

         public void setValueAt(Object value, int row, int col){
             ((Vector) data.get(row)).setElementAt(value, col);
             fireTableCellUpdated(row,col);
         }

         public boolean isCellEditable(int row, int col){
             if (3 == col){
                 return true;
             }
             else {
                return false;
             }
         }

         public void insertData(Object[] values){
             data.add(new Vector());

             for(int i =0; i<values.length; i++){

                 System.out.println("data.size is: " + data.size());
                 ((Vector) data.get(data.size()-1)).add(values[i]);
             }

             fireTableDataChanged();
         }

         public void removeRow(int row){
             data.removeElementAt(row);
             fireTableDataChanged();
         }
     }
}

New attempt at deleting rows of a JTable:

 public void deleteRow() {
 for (int i = 0; i < getRowCount(); i++) {

     Object columnState = getValueAt(i, 3);

     System.out.println("STEP 6 - In row " + i + " boolean value is: " + columnState);

     boolean columnStateAsBoolean = (Boolean) columnState;

     System.out.println("STEP 6 - In row " + i + " Column State As Boolean is: " + columnStateAsBoolean);

     if(columnStateAsBoolean == true) {
         removeRow(i);                   
     }

     System.out.println("-------------------------------------");
 }

}

TokTok123
  • 753
  • 3
  • 11
  • 27
  • Welcome to StackOverflow! StackOverlow is a community of developers who help answer objective questions relating to software development. In its current state, your question is a bit ambiguous. I'd recommend shortening your question and code to only what's relevant to your specific question along with including [what you've tried so far](http://mattgemmell.com/2008/12/08/what-have-you-tried/). You also may want to try giving the [FAQ](http://stackoverflow.com/faq/) a read. Best of luck! – Zach Latta Mar 19 '13 at 00:07
  • @zachlatta There is a question if you intend to read carefully. – Smit Mar 19 '13 at 00:09
  • Smit: It's a big ambiguous. The OP hasn't included what they've tried so far and the code example is far too long for a question like this. – Zach Latta Mar 19 '13 at 00:11
  • *"ANY SUGGESTIONS ARE TRULY APPRECIATED !!!!"* 1) Stop SHOUTING at us! 2) Fix that stuck '!' key. – Andrew Thompson Mar 19 '13 at 03:05
  • .... unrelated: a) don't do any manual sizing/locating **ever**, it's the exclusive task of a suitable layoutManager b) Please learn java naming conventions and stick to them. – kleopatra Mar 19 '13 at 10:11
  • ... and always fire the most focused event, that is a rowsRemoved/rowsInserted (instead of a dataChanged) in remove/insertRows – kleopatra Mar 19 '13 at 10:14

2 Answers2

4

I really want to do is to delete several rows based on boolean states or check boxes

create a loop that starts on the last row and counts down to 0.

Then for every row you use the table.getValueAt(...) method to get the Boolean value of the column.

If the value is true then delete the row.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • @che .. please what did u mean +1 for starts on the last row .. i'm going wrong somewhere with my loop .. i've adjusted my message to include my new attempt .. – TokTok123 Mar 20 '13 at 15:52
  • The advice was to start at the last row and count down to 0. Your code is starting at 0 and counting up to the last row. – camickr Mar 20 '13 at 16:38
  • @AMonari Deletion should start from last row .. instead of starting from the oth row. – Amarnath Mar 20 '13 at 16:43
0

//Try something like this

    int rowCount=table.getSelectedRowCount();//get selected row's count
    int row;
    if(rowCount>0)
    {
       while((row=table.getSelectedRow())!=-1)
        (DefaultTableModel)table.getModel().removeRow(table.convertRowIndexToModel(row));

    }
Prinz Km
  • 323
  • 1
  • 12