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

Asked

Viewed 710 times

-1

I have a Jtable where I have a column by the name of colun1 I want to know how I can alter Jtable’s data when any data on the list that fills it out changes. Example

I have a list with listString name with 3 values

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

Soon in the table would appear 3 lines with the above values.

// 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 decide to change the values of the list Ex:

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

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

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

  • 1

    Vinicius, you need to provide a [mcve], so that we can simulate your problem through a reproducible code.

1 answer

1


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

A solution simple to automate this procedure is to use only the 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 the TableModel. Here an example much simplified:

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 Arraylist, because I prefer to have to implement the necessary methods rather than risk forgetting one of the methods)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.