'Java Index -1 out of bound exception when trying to remove elements from JTable

I was having problem with JTable as I was unable to update and delete data from the table. I was using array list to store data and I was showing the array list's data on the table. The update and delete function are there to at first set row count of table to 0 and then show the updated value of array list on the table. However, it seems that there are some error that I am unable to understand as the program throws Index -1 out of bound exception whenever I click the update or delete button.

My main class :

package dbconnector;
public class Main {
    public Main(){
        Viewer window = new Viewer();
        window.frame.setVisible(true);

    }
    public static void main(String[] args){
        new Main();
    }
}

Data class :

package dbconnector;
public class Data {
    private int id;
    private String name;
    private String address;
    private int salary;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
}

Viewer class :

package dbconnector;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

public class Viewer implements ActionListener, ListSelectionListener {
    private int id_val;
    private String name_val;
    private String addr_val;
    private int salary_val;
    public JFrame frame;
    private JPanel panel;
    private JTable table1;
    private JTextField id_field;
    private JTextField name_field;
    private JTextField addr_field;
    private JTextField salary_field;
    private JPanel p1;
    private JButton new_button;
    private JButton update_button;
    private JButton show_button;
    private JButton delete_button;
    private JLabel id;
    private JLabel name;
    private JLabel address;
    private JLabel salary;
    private JPanel pan1;
    private JPanel pan2;
    private JScrollPane scpan;
    private DefaultTableModel model;
    private ArrayList<Data> al;
    public Viewer(){
        frame = new JFrame("Emploee");
        frame.setContentPane(panel);
        frame.setSize(panel.getPreferredSize());
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.initializer();
    }
    public void initializer(){
        new_button.addActionListener(this);
        update_button.addActionListener(this);
        show_button.addActionListener(this);
        delete_button.addActionListener(this);

        table1.getSelectionModel().addListSelectionListener(this);

        al = new ArrayList<Data>();
        model = new DefaultTableModel();
        table1.setModel(model);
        table1.setDefaultEditor(Object.class,null);
        model.setColumnIdentifiers(new Object[]{"ID","Name","Address","Salary"});
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //Add some code
        if(e.getSource()==this.new_button){
            int id = Integer.parseInt(id_field.getText());
            String name = name_field.getText();
            String addr = addr_field.getText();
            int salary = Integer.parseInt(salary_field.getText());
            Data dt = new Data();
            dt.setId(id);
            dt.setName(name);
            dt.setAddress(addr);
            dt.setSalary(salary);
            al.add(dt);
            model.addRow(new Object[]{dt.getId(),dt.getName(),dt.getAddress(),dt.getSalary()});
            this.fieldCleaner();
        }else if(e.getSource()==update_button){
            int id = Integer.parseInt(id_field.getText());
            String name = name_field.getText();
            String addr = addr_field.getText();
            int salary = Integer.parseInt(salary_field.getText());
            for(Data dt:al){
                if(dt.getId()==id){
                    dt.setName(name);
                    dt.setAddress(addr);
                    dt.setSalary(salary);
                }
            }
            this.showFunction();
            this.fieldCleaner();
        }else if(e.getSource()==show_button){
            //This function will be added later
        }else if(e.getSource()==delete_button){
            int id = Integer.parseInt(id_field.getText());
            for(int i=0;i<al.size();i++){
                Data dt = al.get(i);
                if(dt.getId()==id){
                    al.remove(i);
                }
            }
            this.showFunction();
            this.fieldCleaner();
        }
    }
    @Override
    public void valueChanged(ListSelectionEvent e) {
        //Add some code
        if(!e.getValueIsAdjusting()){
            id_val = Integer.parseInt(table1.getValueAt(table1.getSelectedRow(),0).toString());
            name_val = table1.getValueAt(table1.getSelectedRow(),1).toString();
            addr_val = table1.getValueAt(table1.getSelectedRow(),2).toString();
            salary_val = Integer.parseInt(table1.getValueAt(table1.getSelectedRow(),3).toString());
            id_field.setText(String.valueOf(id_val));
            name_field.setText(name_val);
            addr_field.setText(addr_val);
            salary_field.setText(String.valueOf(salary_val));
        }
    }
    public void showFunction(){
        model.setRowCount(0);
        for(Data dt:al){
            model.addRow(new Object[]{dt.getId(),dt.getName(),dt.getAddress(),dt.getSalary()});
        }
    }
    public void fieldCleaner(){
        id_field.setText("");
        name_field.setText("");
        addr_field.setText("");
        salary_field.setText("");
    }
}

I created it on Intellij , so the viewer.form :

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="dbconnector.Viewer">
  <grid id="27dc6" binding="panel" layout-manager="GridLayoutManager" row-count="2" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
    <margin top="0" left="0" bottom="0" right="0"/>
    <constraints>
      <xy x="20" y="20" width="500" height="400"/>
    </constraints>
    <properties/>
    <border type="none"/>
    <children>
      <grid id="4fbe3" binding="pan1" layout-manager="GridLayoutManager" row-count="6" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
        <margin top="0" left="0" bottom="0" right="0"/>
        <constraints>
          <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
        </constraints>
        <properties/>
        <border type="none"/>
        <children>
          <component id="9850c" class="javax.swing.JLabel" binding="id">
            <constraints>
              <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
            </constraints>
            <properties>
              <text value="Id"/>
            </properties>
          </component>
          <vspacer id="6610">
            <constraints>
              <grid row="5" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
            </constraints>
          </vspacer>
          <component id="858a5" class="javax.swing.JTextField" binding="id_field">
            <constraints>
              <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
                <preferred-size width="150" height="-1"/>
              </grid>
            </constraints>
            <properties/>
          </component>
          <component id="8728" class="javax.swing.JLabel" binding="name">
            <constraints>
              <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
            </constraints>
            <properties>
              <text value="Name"/>
            </properties>
          </component>
          <component id="15012" class="javax.swing.JTextField" binding="name_field">
            <constraints>
              <grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
                <preferred-size width="150" height="-1"/>
              </grid>
            </constraints>
            <properties/>
          </component>
          <component id="34e96" class="javax.swing.JLabel" binding="address">
            <constraints>
              <grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
            </constraints>
            <properties>
              <text value="Address"/>
            </properties>
          </component>
          <component id="6b0e3" class="javax.swing.JTextField" binding="addr_field">
            <constraints>
              <grid row="2" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
                <preferred-size width="150" height="-1"/>
              </grid>
            </constraints>
            <properties/>
          </component>
          <component id="77c11" class="javax.swing.JLabel" binding="salary">
            <constraints>
              <grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
            </constraints>
            <properties>
              <text value="Salary"/>
            </properties>
          </component>
          <component id="e66b0" class="javax.swing.JTextField" binding="salary_field">
            <constraints>
              <grid row="3" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
                <preferred-size width="150" height="-1"/>
              </grid>
            </constraints>
            <properties/>
          </component>
          <grid id="76c79" binding="p1" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
            <margin top="0" left="0" bottom="0" right="0"/>
            <constraints>
              <grid row="4" column="0" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
            </constraints>
            <properties/>
            <border type="none"/>
            <children>
              <component id="d5e96" class="javax.swing.JButton" binding="new_button">
                <constraints>
                  <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
                </constraints>
                <properties>
                  <text value="New"/>
                </properties>
              </component>
              <component id="e5e0" class="javax.swing.JButton" binding="update_button">
                <constraints>
                  <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
                </constraints>
                <properties>
                  <text value="Update"/>
                </properties>
              </component>
              <component id="29e6f" class="javax.swing.JButton" binding="show_button">
                <constraints>
                  <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
                </constraints>
                <properties>
                  <text value="Show"/>
                </properties>
              </component>
              <component id="9db50" class="javax.swing.JButton" binding="delete_button">
                <constraints>
                  <grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
                </constraints>
                <properties>
                  <text value="Delete"/>
                </properties>
              </component>
            </children>
          </grid>
        </children>
      </grid>
      <hspacer id="92d8c">
        <constraints>
          <grid row="0" column="2" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
        </constraints>
      </hspacer>
      <vspacer id="fade8">
        <constraints>
          <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
        </constraints>
      </vspacer>
      <grid id="9727e" binding="pan2" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
        <margin top="0" left="0" bottom="0" right="0"/>
        <constraints>
          <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
        </constraints>
        <properties/>
        <border type="none"/>
        <children>
          <scrollpane id="3bfc3" binding="scpan">
            <constraints>
              <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="7" hsize-policy="7" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
            </constraints>
            <properties/>
            <border type="none"/>
            <children>
              <component id="f52e3" class="javax.swing.JTable" binding="table1" default-binding="true">
                <constraints/>
                <properties/>
              </component>
            </children>
          </scrollpane>
        </children>
      </grid>
    </children>
  </grid>
</form>

Error when delete button is clicked :

/opt/jdk/bin/java -javaagent:/home/tojo/Downloads/app/idea-IC-213.5744.223/lib/idea_rt.jar=42321:/home/tojo/Downloads/app/idea-IC-213.5744.223/bin -Dfile.encoding=UTF-8 -classpath /home/tojo/Documents/java/dbconnector/target/classes dbconnector.Main
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 1
    at java.base/java.util.Vector.elementData(Vector.java:731)
    at java.base/java.util.Vector.elementAt(Vector.java:469)
    at java.desktop/javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:660)
    at java.desktop/javax.swing.JTable.getValueAt(JTable.java:2763)
    at dbconnector.Viewer.valueChanged(Viewer.java:107)
    at java.desktop/javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:224)
    at java.desktop/javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:204)
    at java.desktop/javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:251)
    at java.desktop/javax.swing.DefaultListSelectionModel.removeIndexInterval(DefaultListSelectionModel.java:720)
    at java.desktop/javax.swing.JTable.tableRowsDeleted(JTable.java:4571)
    at java.desktop/javax.swing.JTable.tableChanged(JTable.java:4474)
    at java.desktop/javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:302)
    at java.desktop/javax.swing.table.AbstractTableModel.fireTableRowsDeleted(AbstractTableModel.java:267)
    at java.desktop/javax.swing.table.DefaultTableModel.setNumRows(DefaultTableModel.java:326)
    at java.desktop/javax.swing.table.DefaultTableModel.setRowCount(DefaultTableModel.java:346)
    at dbconnector.Viewer.showFunction(Viewer.java:118)
    at dbconnector.Viewer.actionPerformed(Viewer.java:99)
    at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
    at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)
    at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
    at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
    at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
    at java.desktop/java.awt.Component.processMouseEvent(Component.java:6626)
    at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3389)
    at java.desktop/java.awt.Component.processEvent(Component.java:6391)
    at java.desktop/java.awt.Container.processEvent(Container.java:2266)
    at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5001)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
    at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4948)
    at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4575)
    at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4516)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2310)
    at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2780)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:773)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:722)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:716)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:746)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:744)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:743)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

Process finished with exit code 0

Error when Update button is clicked :

/opt/jdk/bin/java -javaagent:/home/tojo/Downloads/app/idea-IC-213.5744.223/lib/idea_rt.jar=36215:/home/tojo/Downloads/app/idea-IC-213.5744.223/bin -Dfile.encoding=UTF-8 -classpath /home/tojo/Documents/java/dbconnector/target/classes dbconnector.Main
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 1
    at java.base/java.util.Vector.elementData(Vector.java:731)
    at java.base/java.util.Vector.elementAt(Vector.java:469)
    at java.desktop/javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:660)
    at java.desktop/javax.swing.JTable.getValueAt(JTable.java:2763)
    at dbconnector.Viewer.valueChanged(Viewer.java:107)
    at java.desktop/javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:224)
    at java.desktop/javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:204)
    at java.desktop/javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:251)
    at java.desktop/javax.swing.DefaultListSelectionModel.removeIndexInterval(DefaultListSelectionModel.java:720)
    at java.desktop/javax.swing.JTable.tableRowsDeleted(JTable.java:4571)
    at java.desktop/javax.swing.JTable.tableChanged(JTable.java:4474)
    at java.desktop/javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:302)
    at java.desktop/javax.swing.table.AbstractTableModel.fireTableRowsDeleted(AbstractTableModel.java:267)
    at java.desktop/javax.swing.table.DefaultTableModel.setNumRows(DefaultTableModel.java:326)
    at java.desktop/javax.swing.table.DefaultTableModel.setRowCount(DefaultTableModel.java:346)
    at dbconnector.Viewer.showFunction(Viewer.java:118)
    at dbconnector.Viewer.actionPerformed(Viewer.java:87)
    at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
    at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)
    at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
    at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
    at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
    at java.desktop/java.awt.Component.processMouseEvent(Component.java:6626)
    at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3389)
    at java.desktop/java.awt.Component.processEvent(Component.java:6391)
    at java.desktop/java.awt.Container.processEvent(Container.java:2266)
    at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5001)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
    at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4948)
    at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4575)
    at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4516)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2310)
    at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2780)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:773)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:722)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:716)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:746)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:744)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:743)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

Could you guys please help me solve this issue? I was also thinking about adding some jdbc stuff to store the values but I believe that it will not be great if the issue of out of bound exception stays.

The delete and update function not only does not work but also the entire program freezes and the table also does not appear properly. I feel like I am missing something. How do I delete the entire table at first and then add my updated array list to it without out of bound exception?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source