1

I use this method for changing my table cell value, it change on jtable But not change on text file!

public class user_AllBooks extends AbstractTableModel {

    BookInformation book_info = new BookInformation();
    String[] columns = new String[]{"Book Name", "Book Date", "Book ID", "Borrow Status"};
    ArrayList<BookInformation> bData = new ArrayList<BookInformation>();

    public user_AllBooks() {
        try {
            BufferedReader br = new BufferedReader(new FileReader("AllBookRecords.txt"));
            String line;
            while ((line = br.readLine()) != null) {
                bData.add(initializeBookData(line));
            }
            br.close();
        } catch (IOException ioe) {
        }
    }

    public BookInformation initializeBookData(String myline) {
        BookInformation book_infos = new BookInformation();
        String[] celledLine = myline.split("     ");
        book_infos.setBookName(celledLine[0]);
        book_infos.setBookDate(celledLine[1]);
        book_infos.setBookID(celledLine[2]);
        book_infos.setBorrowStatus(celledLine[3]);
        return book_infos;
    }

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

    @Override
    public int getRowCount() {
        if (bData != null) {
            return bData.size();
        } else {
            return 0;
        }
    }

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

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        BookInformation bookInf = bData.get(rowIndex);
        Object value;

        switch (columnIndex) {
            case 0:
                value = bookInf.getBookName();
                break;
            case 1:
                value = bookInf.getBookDate();
                break;
            case 2:
                value = bookInf.getBookID();
                break;
            case 3:
                value = bookInf.getBorrowStatus();
                break;
            default:
                value = "...";
        }
        return value;
    }


    @Override
  public void setValueAt(Object value, int row, int col)
    {
    BookInformation book_infos = bData.get(row);
    if (col==0)
    book_infos.setBookName((String)value);
    else if (col==1)
    book_infos.setBookDate((String)value);
    else if (col==2)
    book_infos.setBookID((String)value);
    else if (col==3)
    book_infos.setBorrowStatus((String)value);
    }
    }

Second Class:

public class user_AllBooksM extends JFrame implements ActionListener {

    user_AllBooks uAllBooks = new user_AllBooks();
    final JTable bTable = new JTable(uAllBooks);
    JButton borrowButton;

    public user_AllBooksM() {
        setTitle("All Books");
        exitButton = new JButton("Exit");
        borrowButton = new JButton("Borrow");
        borrowButton.addActionListener(this);
        JPanel Bpanel = new JPanel();
        Bpanel.setLayout(new FlowLayout());
        JScrollPane sp = new JScrollPane(bTable);
        Bpanel.add(sp);
        Bpanel.add(borrowButton);
        this.add(Bpanel);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setBounds(300, 60, 550, 550);
        this.setResizable(false);
        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        borrowInitialize(bTable.getSelectedRow());
    }

    public void borrowInitialize(int row) {
        if (uAllBooks.getValueAt(row, 3).equals("yes")) {
            JOptionPane.showMessageDialog(null, "This Book Was Borrowed");
        } else {
            uAllBooks.setValueAt("Yes", row, 3);
            uAllBooks.fireTableRowsUpdated(row, row);
        }
    }

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

My Text File:

sds wew     88     77     no
moon     889     988     yes
ccc     30     33     no
testing     76     77     no
yes     999     444     no
hoop     100     200     no
name     60     20     no
pp     14     15     no
vbnet     49     94     yes
sdsd     232     dsds     no
gh     12     21     no
khoyBook     322     233     no
Sajad
  • 2,273
  • 11
  • 49
  • 92

2 Answers2

4

Add a TableModelListener to your TableModel. Then whenever an update event is first you will need to loop through the row/columns of your TableModel and recreate your text file.

Your TableModel is implemented incorrectly. You have not implemented the setValueAt(...) method.

The "fireTableRowsUpdated()" method should be invoked from the setValueAt() method of your TableModel. It should not be invoked from your ActionListener code.

camickr
  • 321,443
  • 19
  • 166
  • 288
1

To change the Content of file when cell value is changed , You should register the TableModelListener to the associated TableModel . And implement the file writing Logic in tableChanged method.
Here is the sample code that demonstrates how to implement TableModelListener . I hope this would provide you a good view to achieve your task:

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.event.TableModelListener;
import javax.swing.event.TableModelEvent;
import javax.swing.table.TableModel;
import javax.swing.table.AbstractTableModel;
class TableDemo extends JFrame  implements TableModelListener
{
    private JTable table;
    private JScrollPane jsPane;
    private TableModel myModel;
    private JLabel label;
    public void prepareAndShowGUI()
    {
        myModel = new MyModel();
        table = new JTable(myModel);
        jsPane = new JScrollPane(table);
        label = new JLabel();
        myModel.addTableModelListener(this);
        getContentPane().add(jsPane);
        getContentPane().add(label,BorderLayout.SOUTH);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }
    @Override
    public void tableChanged ( TableModelEvent evt)
    {
        int row = evt.getFirstRow();
        int col = evt.getColumn();
        label.setText("Value at ["+row+"]["+col+"] is changed to: "+myModel.getValueAt(row,col));
           //Write to your file here.
    }
    private class MyModel extends AbstractTableModel 
    {
        String[] columns = {
                            "Roll No.",
                            "Name"
                            };
        String[][] inData = {
                                {"1","Anthony Hopkins"},
                                {"2","James William"},
                                {"3","Mc. Donald"}
                            };
        @Override
        public void setValueAt(Object value, int row, int col)
        {
            inData[row][col] = (String)value;
            fireTableCellUpdated(row,col);
        }
        @Override
        public Object getValueAt(int row, int col)
        {
            return inData[row][col];
        }
        @Override
        public int getColumnCount()
        {
            return columns.length;
        }
        @Override 
        public int getRowCount()
        {
            return inData.length;
        }
        @Override
        public String getColumnName(int col)
        {
            return columns[col];
        }
        @Override 
        public boolean isCellEditable(int row, int col)
        {
            return true;
        }
    }
    public static void main(String st[])
    {
        SwingUtilities.invokeLater( new Runnable()
        {
            @Override
            public void run()
            {
                TableDemo td = new TableDemo();
                td.prepareAndShowGUI();
            }
        });
    }
}
Vishal K
  • 12,976
  • 2
  • 27
  • 38
  • Can you write my write to file method? – Sajad Feb 13 '13 at 19:24
  • What should be writed to file? – Sajad Feb 13 '13 at 19:24
  • Should i write to file a line or a cell value? – Sajad Feb 13 '13 at 19:28
  • Each line in my table row has 4 elements. – Sajad Feb 13 '13 at 19:29
  • @Sajjad-HiFriend: File I/O is not that much complicated. You should created new File in `tableChanged` method. Iterate over each cell of the `tablemodel` and retrieve value. Add each value to a `StringBuilder`.For each row after you add the cell value to `StringBuffer` add `"\t"` to `StringBuffer` . And After a row is read add `"\n"` to `StringBuffer`. After entire `table` is read write the contents of StringBuffer to File using FileWriter or `BufferedWriter` – Vishal K Feb 13 '13 at 19:39
  • Click this tutorial for File I/O http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html – Vishal K Feb 13 '13 at 19:55