-3

I try for almost 2 hours to figure out how to remove and update 1 row from a JTable but somehow it wont work. I use the following code:

DefaultTableModel modelTable = (DefaultTableModel) jTabelRooster.getModel();

modelTable.addRow(new Object[]{lid.getLidnummer().toString(), lid.getLidvoornaam(), lid.getLidtussenvoegsel(),lid.getLidachternaam(), lid.getAanwezig()});

Ok so far so good.. rows are nicely added.. but now i would like to remove them:

int SelectedRow = jTabelRooster.getSelectedRow();
modelTable.removeRow(SelectedRow);

When i do this i get the following error: Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2

Your help would be appreciated

EDIT: the jTabelRooster has been inserterd by the gui layout manager So i have this code now, and i dont get much succes:

private void initRoosterDetail()
{
   for(int i = 0; i < leden.size(); i++)
        {
            lid = leden.get(i);

            modelTable.addRow(new Object[]{lid.getLidnummer().toString(), lid.getLidvoornaam(), lid.getLidtussenvoegsel(),lid.getLidachternaam(), lid.getAanwezig()});

        }
}
private void jbInschrijvingVerwijderenActionPerformed(java.awt.event.ActionEvent evt) {                                                          
        int SelectedRow = jTabelRooster.getSelectedRow();
        modelTable.removeRow(jTabelRooster.convertRowIndexToModel(SelectedRow));
  }  

this must be it :)

When i select 1 row in the table and press the cancelbutton.. i receive this message:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2

========================================================================================================================================================================================================================================================================================================================================

Thanx all for the help... i know what i did wrong... it had to do with a tableModelListener i used.. so this left me with another problem :)

 jTabelRooster.getModel().addTableModelListener(
        new TableModelListener()
        {
        public void tableChanged(TableModelEvent evt) 
        {
             if(jTabelRooster.getSelectedColumn() == 4)
             {
              }
    }

});

This code was messing the deleterow command.

I have 1 boolean column with checkboxes in it :(

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user2445977
  • 1
  • 1
  • 2
  • 6
  • 2
    Suggestion for getting a quick decent answer here: create and post a very small compilable, runnable example program that we can run unaltered and that demonstrates your problem, an [sscce](http://sscce.org). – Hovercraft Full Of Eels Jun 22 '13 at 19:40
  • As suggested by @HovercraftFullOfEels Post the SSCCE or at least the relevant methods of your code so that we don't have to bang head to make wild guesses about the reasons for errors...My Quick question..show the method where you are creating `modelTable` object – Vishal K Jun 22 '13 at 19:48
  • 1
    @user2445977: Please don't post code in comments since it looses all formatting and becomes unreadable. Instead edit your question with your new code. And about that [sscce](http://sscce.org), the sooner you post it, the sooner you'll get a correct answer. Also consider replying to answers to your other questions on this site. We are volunteers and like to know that you have taken the time to read our contributions and whether or not it has helped. Your replies will help motivate others to help you more. – Hovercraft Full Of Eels Jun 22 '13 at 20:04
  • Ok.. thank you very much for the support.. i add some extra code now – user2445977 Jun 22 '13 at 20:25
  • Please add the stack trace for the exception – Elist Jun 22 '13 at 21:12
  • @user2445977, `i know what i did wrong... it had to do with a tableModelListener i used` - you got that advice in you last question, so it would be nice to accept the answer that you used. But more importantly it would be even better if you actually followed the advice given to you in your last question. Then you wouldn't have this problem and people would not be spending time reading this question. Hint: a "delete" is different than an "update". You don't want to execute your code on a delete. – camickr Jun 23 '13 at 17:46

2 Answers2

2
int selectedRow = jTabelRooster.getSelectedRow();
modelTable.removeRow(SelectedRow);

If no row is selected then jTabelRooster.getSelectedRow() will return -1

So before you delete check whether a row is selected or not.

int selectedRow = jTabelRooster.getSelectedRow();
if(selectedRow != -1) {
    modelTable.removeRow(selectedRow);
}

P.S: Try to follow java naming conventions. Variable name should start with a lowercase.

EDIT: An example which shows how to add and remove rows using DefaultTableModel from a table.

private void createUI() {
        JFrame frame = new JFrame();

        frame.setLayout(new BorderLayout());

        final JTable table = new JTable();
        final DefaultTableModel model = new DefaultTableModel(5, 3);
        table.setModel(model);

        JPanel btnPnl = new JPanel(new BorderLayout());
        JPanel bottombtnPnl = new JPanel(new FlowLayout(FlowLayout.CENTER));

        JButton addBtn = new JButton("Add");
        JButton deleteBtn = new JButton("Remove");
        bottombtnPnl.add(addBtn);
        bottombtnPnl.add(deleteBtn);

        addBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                model.addRow(new Object[]{});
            }
        });

        deleteBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int selRow = table.getSelectedRow();
                if(selRow != -1) {
                    model.removeRow(selRow);
                }
            }
        });

        btnPnl.add(bottombtnPnl, BorderLayout.CENTER);

        table.getTableHeader().setReorderingAllowed(false);

        frame.add(table.getTableHeader(), BorderLayout.NORTH);
        frame.add(table, BorderLayout.CENTER);
        frame.add(btnPnl, BorderLayout.SOUTH);

        frame.setTitle("JTable Example.");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
Amarnath
  • 8,736
  • 10
  • 54
  • 81
  • 2
    This also is a good suggestion, one that should be followed, but is not likely to be the cause of the error. By the error message, `java.lang.ArrayIndexOutOfBoundsException: 2 >= 2`, we know that `getSelectedRow()` is returning 2, but also know that the rowCount is already 2. There's something going on that the original poster is not showing us still. We have requested more information, information that will allow us to not have to guess at an answer, but for unknown reasons, he is still holding more information back from us. – Hovercraft Full Of Eels Jun 22 '13 at 20:23
  • @HovercraftFullOfEels AFAIK I still don't understand how OP is getting selected row as 2 if there are only 2 rows in the table. Since the index of these rows will {0, 1}. – Amarnath Jun 22 '13 at 20:54
  • I do have some succes now.. i use selectedRow - 1 However.. i cant get rid of the very first row somehow :) – user2445977 Jun 22 '13 at 21:09
  • @HovercraftFullOfEels, I'm not sure about what `convertRowIndexToModel` returns in case it gets -1. It says that it throws `IndexOutOfBoundException` in case the index is bigger then `getRowCount()`, but it might return some unexpected value (maybe 2 in this case...) for -1. – Elist Jun 22 '13 at 21:15
  • @user2445977 Refer the EDIT post. I have added an example. It shows how to add and delete rows from a table. – Amarnath Jun 22 '13 at 21:27
  • I have a problem? In my JTable it always show the selected row as -1 .Why is that? – chamzz.dot Nov 12 '17 at 17:37
  • @chamzz.dot Default value if nothing is selected. [see this](https://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html#getSelectedRow()) – Amarnath Nov 13 '17 at 07:19
2

All we can say based on this code:

private void jbInschrijvingVerwijderenActionPerformed(java.awt.event.ActionEvent evt) {                                                          
    int SelectedRow = jTabelRooster.getSelectedRow();
    modelTable.removeRow(jTabelRooster.convertRowIndexToModel(SelectedRow));
}

and this error:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2

is that somehow your TableModel held by modelTable is out of sync with the actual model that is held by the jTabelRooster JTable, and that's about it. We know this because your selected row in the JTable is row number 2 which is the 3rd row, but your model held by modelTable is showing that it holds only 2 rows. How or why this is occurring is impossible for us to guess based on the limited information that you've presented so far.

Again, you should strongly consider creating and posting an sscce.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373