1

I try to remove all the row of a Jtable before add new row. But for some reason i can't remove a row.

In the ModelDynamiqueObjet i define all the override methods and then i add two methods one to add an object and the an other to remove an objet.

I succes to add serverals object but when i try to delete some object of the arraylist i failed . This is my class with the AbstractModel :

public class ModeleDynamiqueObjet extends AbstractTableModel {
private ArrayList<Meteo> meteos ;
private String[] entetes = {"Date", "Temps", "Temperature", "Vent", "Humidité", "Nuage"};


public ModeleDynamiqueObjet() {
    super();
    meteos = new ArrayList<Meteo>();
}

@override methods....

public void addRow(Meteo meteo) {
    meteos.add(meteo);
    fireTableRowsInserted(meteos.size() -1, meteos.size() -1);
}

public void removeRow(int index){
    meteos.remove(index);
    fireTableRowsDeleted(index,index);

}

}

This is my view :

public class Fenetre extends JFrame implements Observer, ActionListener {
private JTextField adresseField;
private ModeleDynamiqueObjet model;
private JTable tableau;
private JScrollPane scrollPane;

private Controller controller = null;

public Fenetre(Controller controller) {
    super("Ma météo");
    this.controller = controller;

    GraphicsEnvironment.getLocalGraphicsEnvironment();
    this.setSize(800,800);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(new BorderLayout());
    model = new ModeleDynamiqueObjet();
    tableau = new JTable(model);
    scrollPane = new JScrollPane(tableau);
    getContentPane().add(new JScrollPane(scrollPane), BorderLayout.CENTER);
    this.setVisible(true);
}

@Override
public void update(Observable o, Object arg) {

    if(o instanceof MeteoAPI ){
        MeteoAPI meteoAPI = (MeteoAPI) o;
        ArrayList<Meteo> meteos = new ArrayList<Meteo>(meteoAPI.getMeteos());

        for(int i =0 ; i < model.getRowCount(); i++){
            model.removeRow(i);
        }

        for (Meteo meteo : meteos) {
            model.addRow(meteo);
        }

         this.setVisible(true);
    }
} }

If someone can tell me what i'm doing wrong. Thx for your help

Thoril
  • 11
  • 2

1 Answers1

1

Your loop must be counterwise, cause the last indexes will not be available cause you removed the previous ones and the count is lesser than 'i'.

Also, easier:

Instead of calling each removeRow (that should be counterwise to work)

for (int i = model.getRowCount() - 1; i >= 0; i--)

Just clear the list from the model, add this to the TableModelImplClass

public void removeAll(){
    int size = meteos.size();
    meteos.clear();
    fireTableRowsDeleted(0, size);
}

And call it instead of the loop

Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167