1

I have a table that read records from file and display them and have a delete button that when user select a row and clicked, that line delete from table and text file too.

(Updated)

public class Readuser_A extends AbstractTableModel {

String[] columns = { "Fname", "Lname", "Gender", "Date", "ID" };
ArrayList<String> Listdata = new ArrayList<String>();
String[][] Arraydata;

public Readuser_A() {
    try {
        FileReader fr = new FileReader("AllUserRecords.txt");
        BufferedReader br = new BufferedReader(fr);
        String line;
        while ((line = br.readLine()) != null) {
            Listdata.add(line);
        }
        br.close();
        Arraydata = new String[Listdata.size()][];
        for (int i = 0; i < Listdata.size(); i++) {
            Arraydata[i] = Listdata.get(i).split("     ");
        }
    } catch (IOException e) {
    }
}

 public void RemoveMyRow(int row){
  Listdata.RemoveElement(row);
   }

@Override
public String getColumnName(int colu) {
    return columns[colu];

}

public int getRowCount() {
    if (null != Arraydata) {
        return Arraydata.length;
    } else {
        return 0;
    }
}

public int getColumnCount() {
    return columns.length;
}

public Object getValueAt(int rowIndex, int columnIndex) {
    return Arraydata[rowIndex][columnIndex];
}
}

My second Class:

public class ReaduserM_A {
final JLabel myLable = new JLabel();

public ReaduserM_A() {

    final Readuser_A RU = new Readuser_A();
    final JTable mytable = new JTable(RU);
    final JFrame Uframe = new JFrame("All Users");
    JButton DellButton = new JButton("Delete User");

    DellButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (mytable.getSelectedRow() != -1) {
                removeRow(mytable.getSelectedRow());
                RU.fireTableRowsDeleted(mytable.getSelectedRow(),
                        mytable.getSelectedRow());
            } else {
                JOptionPane.showMessageDialog(null, "No Row Selected");
                return;
            }

            //Now, Delete from text file too
            deleteFromFile();
        }

    });

    JPanel panel = new JPanel();
    JScrollPane sp = new JScrollPane(mytable);
    panel.add(sp);
    panel.add(DellButton);
    panel.add(myLable);
    Uframe.add(panel);
    Uframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Uframe.setSize(570, 500);
    Uframe.setLocation(300, 60);
    Uframe.setVisible(true);
}

public void deleteFromFile() {
    File Mf = new File("AllUserRecords.txt");
    File Tf = new File("Uoutput.txt");
    try {
        FileReader Ufr = new FileReader(Mf);
        BufferedReader Ubr = new BufferedReader(Ufr);
        PrintWriter Upw = new PrintWriter(new FileWriter(Tf));
        String Us;
        while ((Us = Ubr.readLine()) != null) {
            String[] Ust = Us.split("     ");
            String Unumber = Ust[4];

            //How find the selected row line by it's ID and delete that row?
        }
        Upw.close();
        Ubr.close();
        Mf.delete();
        Tf.renameTo(Mf);

    } catch (FileNotFoundException e1) {
        myLable.setText("File Not Found");
    } catch (IOException ioe) {
        myLable.setText("IO Error");
        ioe.printStackTrace();
    }
}

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

Thank you

tkanzakic
  • 5,499
  • 16
  • 34
  • 41
Sajad
  • 2,273
  • 11
  • 49
  • 92

1 Answers1

2
removeRow(mytable.getSelectedRow());

Above statement may be the problem. Because if there is no selected row then getSelectedRow returns -1.

Check whether the row exists or not. Then delete if it exists.

if(mytable.getSelectedRow() != -1) {
  removeRow(mytable.getSelectedRow());
}

UPDATE:

I ran your code I got NullPointerException in getRowCount method of your TableModel class.

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

So do a null check before you get the count.

public int getRowCount() {
if(null != Arraydata) {
    return Arraydata.length;
} else {
    return 0;
}
}

Now if you run you will get the ArrayOutOfBoundException with index -1. This is because of the delete action. As I stated earlier, check whether row exists or not then do the respective action. The following code does that.

public void actionPerformed(ActionEvent e) {
    if(mytable.getSelectedRow() != -1) { 
      removeRow(mytable.getSelectedRow());
      rftl2.fireTableRowsDeleted(mytable.getSelectedRow(), mytable.getSelectedRow());
    } else {
      JOptionPane.showMessageDialog(null, "No Row Selected");
       return;
    }

    //Now, Delete from text file too
    deleteFromFile();
 }

Finally you get the output (if there is no selected row like this.)

enter image description here

Amarnath
  • 8,736
  • 10
  • 54
  • 81
  • @Sajjad-HiFriend Please look at my update. As I have said there is an issue with **removeRow(mytable.getSelectedRow());** and prior to that there is another issue with the initialization of the **Arraydata** in your model class. I have changed the respective method. Your code works fine now. – Amarnath Jan 26 '13 at 02:28
  • Hello, Not Work yet, my new exception is this: – Sajad Jan 29 '13 at 13:12
  • Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 6 >= 0 at java.util.Vector.removeElementAt(Vector.java:554) at ... – Sajad Jan 29 '13 at 13:13
  • I think that In First Line, ArrayIndexOutOfBoundsException: 6 >= 0 mean that my table row that selected(I selected sixth row and clicked delete button) Can you help me more? – Sajad Jan 29 '13 at 13:14
  • @Sajjad-HiFriend Can you update the _Post_ by showing the new code with data in the table's along with the delete buttons. B'coz previous posted code does not have any data in the table. – Amarnath Jan 29 '13 at 13:17
  • I remove Extends defaulttable model from ReadUserFileToListM2 and just use one model and defined a remove row method on ReadUserFileToList2. – Sajad Jan 29 '13 at 15:38
  • When r u getting the error. Since when I run I am not getting any error. What is the scenario of the error. – Amarnath Jan 29 '13 at 15:46
  • Oh, When i select a row and clicked button, make no sense! – Sajad Jan 29 '13 at 16:04
  • Sorry for cumbersome issue! – Sajad Jan 29 '13 at 16:06
  • @Sajjad-HiFriend The problem is when I run your code there are no rows in first case. If there are rows I could have seen the issue and try to solve it. Your table is empty so I can't you much. Insert rows and I will delete one and check the issue. – Amarnath Jan 29 '13 at 16:14
  • Please create a text file with the name "AllUserRecords.txt" and fill like this: – Sajad Jan 29 '13 at 16:34
  • jone brown male 2011 69 – Sajad Jan 29 '13 at 16:35
  • Five Space must inserted after each fname lname gender date and id. – Sajad Jan 29 '13 at 16:36