How to dynamically change model data when changing value from the list that fills it?

-1

I have a JTable where I have a column named colun1 I want to know how do I change the JTable data when any data in the list that fills it changes. Example

I have a list with name of listString with 3 values

"String 1"
"String 2"
"String 3"

Next to the table would appear 3 lines with the values above.

// preencher a  table
 public void preencheTable(List<String> listString){
  DefaultTableModel defaultTableModel = (DefaultTableModel) jtable.getModel();
        defaultTableModel.setRowCount(0);
        for (String s : listString) {
            defaultTableModel.addRow(new Object[]{
             s
            });
        }


}

Then at some point I resolve to change the values in the list Ex:

//chamo um metodo que adiciona uma nova String na lista que preenche a table.

public void mudarLista(){    
listaString.add("Nova String");
}

What event do I have to call or implement so that in JTable the model updates automatically. (Whenever the contents of the list are changed, the Jtable columns are also changed). In this case the table would have the 3 values from before plus the value "New String" in the fourth line.

    
asked by anonymous 13.12.2017 / 17:16

1 answer

1

You simply update the defaultTableModel that it will generate the events needed to update the JTable.

A simple solution to automate this procedure is to only use DefaultTableModel to save the data instead of List ... (gambiarra?)

Probably better, more flexible, especially if the application is not very simple, is to create (extend) a list that also implements TableModel . Here is a very simplified example:

public class MinhaLista {

    private final List<String> lista = new ArrayList<>();
    private final Modelo modelo = new Modelo();


    public TableModel getTableModel() {
        return modelo;
    }

    public int size() {
        return lista.size();
    }

    public String get(int index) {
        return lista.get(index);
    }

    public boolean contains(Object o) {
        return lista.contains(o);
    }

    public boolean add(String e) {
        boolean added = lista.add(e);
        if (added) {
            int row = lista.size()-1;
            modelo.fireTableRowsInserted(row, row);
        }
        return added;
    }

    public String remove(int index) {
        String removed = lista.remove(index);
        modelo.fireTableRowsDeleted(index, index);
        return removed;
    }

    public void clear() {
        lista.clear();
        modelo.fireTableDataChanged();
    }

    public MinhaLista() {
    }

    private class Modelo extends AbstractTableModel {

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            if (columnIndex != 0)
                throw new IndexOutOfBoundsException("column: " + columnIndex);
            return String.class;
        }

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

        @Override
        public int getColumnCount() {
            return 1;
        }

        @Override
        public Object getValueAt(int row, int column) {
            if (column != 0)
                throw new IndexOutOfBoundsException("column: " + column);
            return lista.get(row);
        }
    }
}

Used as in:

public class TestMinhaLista {

    private static final MinhaLista lista = new MinhaLista();
    private static final JTextField status = new JTextField();

    public static void main(String[] args) {
        JTable table = new JTable(lista.getTableModel());

        JButton add = new JButton("add");
        add.addActionListener(TestMinhaLista::add);
        JButton remove = new JButton("remove");
        remove.addActionListener(TestMinhaLista::remove);
        JButton clear = new JButton("clear");
        clear.addActionListener(TestMinhaLista::clear);
        JPanel panel = new JPanel();
        panel.add(add);
        panel.add(remove);
        panel.add(clear);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(frame.DISPOSE_ON_CLOSE);
        frame.add(panel, BorderLayout.PAGE_START);
        frame.add(new JScrollPane(table), BorderLayout.CENTER);
        frame.add(status, BorderLayout.PAGE_END);
        frame.setSize(400, 400);
        frame.validate();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static void add(ActionEvent ev) {
        int num = lista.size() + 1;
        lista.add("linha " + num);
        status.setText("linha " + num + " adicionada");
    }

    private static void remove(ActionEvent ev) {
        if (lista.size() > 0) {
            int index = (int) (Math.random() * lista.size());
            String texto = lista.remove(index);
            status.setText("linha " + (index+1) + " removida: " + texto);
        } else {
            status.setText("nada para apagar");
        }
    }
    private static void clear(ActionEvent ev) {
        lista.clear();
        status.setText("lista serada");
    }
}

(I used delegation instead of extending the ArrayList because I'd rather have to implement the required methods rather than the risk of forgetting one of the methods)     

14.12.2017 / 15:21