Modify the indexes of each item in a TreeView Java FX or override method TreeView.getSelectionModel (). select (int index)?

2

Greetings to all. This is my first post here.

I'm developing a Java FX project that consists of a form with a TreeView whose items are obtained from an ArrayList, previously populated through a query to the database.

Thistablerepresentsahierarchyofitemswhereeachitemhasanid,name,andaparent_id(idofanothertableitem,takenastheparentoftheiteminquestion).

TomounttreeI'musingaforeachtoselecttheiteminthetreewhoseidcorrespondstotheparent_id(c.getParent)ofeachitemtobeadded:

for(Contac:list){try{tree.getSelectionModel().select(c.getParent());MyTreeItemitem=(MyTreeItem)tree.getSelectionModel().getSelectedItem();item.setExpanded(true);MyTreeItemconta=newMyTreeItem(c.getNome(),c.getId());item.getChildren().add(conta);}catch(Exceptione){System.out.println(e);}}

ThismethodworkedasIexpected:

WhenIexecutedtheprojectthefirsttimethetablealreadyhadtherecordsandthetreewasmountedcorrectly.ThenIimplementedmethodstoaddchildrentoanynodeselectedbytheuser.TheproblemisthatIrealizedthatalthoughthemethodissavingthenewitemcorrectlyintheDB(seeimagebelow),ifIupdatethetree,orcloseandopentheprogramagain,thetreewillshowthenewlyaddeditemasthechildofaitemotherthanwhathadbeenchosenandwhichispointedtobytheparente_idfieldasparent.

Notethattheitem"Current Account 6666" (parent_id = 15) should be the child of the "Bank of Boston" account (id = 15)

So I created a custom TreeItem with the parameters id and name to at the time of mounting the tree trying to organize the hierarchy using as a criterion the id that the element represented in the tree has in the database. It was then that I realized that the problem is in this line: tree.getSelectionModel().select(c.getParent()); because it selects the item by index in Treeview, except that this index does not correspond to the id of the element in the database.

My question is how do I make the line of code tree.getSelectionModel().select(int index); select an item in a TreeView not by the index parameter (position of the item in the TreeView (?)), but using the identifier ) that I created in a TreeItem-derived class with this attribute.

Thanks to all of you right away.

    
asked by anonymous 04.04.2018 / 04:51

1 answer

1

I did a little different from your proposal and for me it worked correctly, I'll explain step by step how I did it:

List<TreeItem<Conta>> treeItems = new ArrayList<>();

// Criando todos os tree itens
for (Conta c: contas) {
    TreeItem<Conta> newItem = new TreeItem<Conta>(c);
    treeItems.add(newItem);
}

// Adicionando filhos dos nós
for (TreeItem<Conta> no : treeItems) {
    // Pega o id do nó
    int id = no.getValue().getId();

    // Busca os nós que tem como parentId o id do pai
    List<TreeItem<Conta>> filhos = treeItems.stream()
                .filter( filho -> filho.getValue().getParent_id() == id)
                .collect(Collectors.toList());

    // Adiciona-os como filhos
    no.getChildren().setAll(filhos);
}

// Adiciona o nó root na árvore 
TreeView<Conta> tree = new TreeView<>(treeItems.get(0));

First I created all the TreeItems from the array of accounts, and only then did I navigate through the created nodes and add the children. So far I do not know if it is very different but I do not know if you noticed that TreeItem accepts a type through Generics.

Note: In order for the object name in the TreeView to not be strange you have to override the toString method of the account class like this:

@Override
public String toString() {
    return nome; // Vai retornar apenas o nome do objeto como representação
}

To add new nodes I did the following:

Button adicionarNo = new Button("Adicionar nó");
adicionarNo.setOnAction((ActionEvent) -> {
    // Pega uma referência ao item selecionado ao invés de usar o Index
    TreeItem<Conta> itemSelecionado = tree.getSelectionModel().getSelectedItem();

    // Verifica se a seleção não está vazia, para evitar NPE
    if(itemSelecionado != null) {
        int idpai = itemSelecionado.getValue().getId();

        // Adiciona a conta no banco de dados,
        // Aqui você pode retornar o id da nova conta criada no banco
        int idconta = 0; //adicionaConta("Nome do item", idpai);

        TreeItem<Conta> novoItem = new TreeItem<Conta>(new Conta(idconta, idpai, "Nome do item"));
        itemSelecionado.getChildren().add(novoItem);
   }
});

That way I was able to create new nodes anywhere in the tree without any problems.

    
09.05.2018 / 20:53