Observable List in a list View Javafx

Asked

Viewed 644 times

0

I need help with a code, this code is just an example that I’m trying to implement, my idea is like a sales screen where I would be adding in List View products to be registered in a sale later, my idea is that every time the add button runs between the ID and the Name in the list view at the bottom line, without disappearing with the others that have already been added, however it is returning null. Any hint?

//CONTROLLER

public class TelaFXController implements Initializable {

    @FXML
    private TextField txtID;
    @FXML
    private TextField txtNome;
    @FXML
    private TableView<Teste> tbvTeste;
    @FXML
    private TableColumn<Teste, Integer> tbcID;
    @FXML
    private TableColumn<Teste, String> tbcNome;
    @FXML
    private Button btnADD;

    private List<Teste> listaTeste = null;

    @Override
    public void initialize(URL url, ResourceBundle rb) {

    }    

    @FXML
    private void btnADD_Click(ActionEvent event) {

        Teste teste = new Teste();

        teste.setID(Integer.parseInt(txtID.getText()));
        teste.setNome(txtNome.getText());

        listaTeste.add(teste);

        atualizarTabela();
    }

    private void atualizarTabela(){
        ObservableList<Teste> obsTeste;
        obsTeste = FXCollections.observableArrayList(listaTeste);

        tbcID.setCellValueFactory(new PropertyValueFactory("ID"));
        tbcNome.setCellValueFactory(new PropertyValueFactory("nome"));

        tbvTeste.setItems(obsTeste);
    } 
}

//CLASS

public class Teste {

    private int ID;
    private String nome;

    public int getID() {
        return ID;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }
}

2 answers

1

You are setting up Tableview again every time you call the updateTable method. In fact, if you define an Observablelist, using the method setItems of your Tableview, the changes in the former reflect in the latter because of the Observer design pattern.

So my suggestion is this::

@Override
public void initialize(URL url, ResourceBundle rb) {
    obsTeste = FXCollections.observableArrayList();

    tbcID.setCellValueFactory(new PropertyValueFactory("ID"));
    tbcNome.setCellValueFactory(new PropertyValueFactory("nome"));

    tbvTeste.setItems(obsTeste);
}

@FXML
private void btnADD_Click(ActionEvent event) {
    Teste teste = new Teste();

    teste.setID(Integer.parseInt(txtID.getText()));
    teste.setNome(txtNome.getText());

    obsTeste.add(teste);
}

1

you are not instantiating listTthis, try listTeste = new Arraylist<>();

Browser other questions tagged

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