Pedro Pedro - 5 months ago 22
Java Question

Notify when source is updated

I have two cells in a sheet in a Java program (a kind of an Excel program) and I want to make a method that will repeat itself everytime these cells are updated.

More specifically, every time a user changes the cells on the sheet I have to repeat a method that will import the information of the cells to a list. So I will need to repeat this method automatically x times, depending on the cells behavior.

Any ideas how to do this?

Answer

Add a listener (for JTextFeild its DocumentListener) to the text field(or whatever your cell is), which is automatically created for you.

// Listen for changes in the text
textField.getDocument().addDocumentListener(new DocumentListener() {
  public void changedCell(DocumentEvent e) {
    update();
  }
  public void removeCell(DocumentEvent e) {
    update();
  }
  public void addCell(DocumentEvent e) {
    update();
  }

  public void update() {
     if (Integer.parseInt(textField.getText())<=0){
       // Do update 
     }
  }
});