Update Jeditorpane as a function’s data return - JAVA

Asked

Viewed 109 times

3

Basically, the situation is this, I have a Java application that communicates with an API to update a database. The problem I face is this, I’m doing the process as follows:

Application Class

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
        int idTipo=cmbTipos.getSelectedIndex()+1; 
        if(idTipo!=-1)//verifica se algum item foi selecionado
        {
            ApiFipe.GetsMarcas client = new ApiFipe.GetsMarcas();
            jedpAtualizados.setContentType("text/html");//define que o tipo de conteúdo do JEditorPane será text/html
            jedpAtualizados.setText(client.Get(idTipo));// aqui defino que o conteúdo será o que retornar da função que recebe os dados da api, e conforme os salva no banco de dados, concatena os dados que foram salvos em uma String e retorna essa String.
            cmbTipos.setSelectedIndex(-1);//reseta o combobox
            JOptionPane.showMessageDialog(null,"Categoria atualizada com sucesso!");//avisa que a operação foi realizada com sucesso
        } 

Getsmarcas class

private String get(int idTipo)
{
    String retorno="";
    //recebe dados de uma api
    while(dadosdaapi.next()){
       //salva esses dados em um banco de dados
       retorno+=Integer.toString(objdedados.getCodigo());
   }
   return retorno;
}

This way, the application is "locked" until all the data of the api is saved and the function returns, what I would like to do is present the code of each item that was saved as soon as this occurred, thus updating the user on the progress of the update.

  • Does this api provide the data individually? or does it bring all brands at once?

1 answer

4


Neto I’m updating again the answer because it really gets hard to understand where your problem is.

resposta antiga

the jop (JOptionPane) it’s not a good case you want a screen to appear in the user’s face stating that such an operation has been completed, yet more if it is inside a while loop. Imagine if it is 50 repetitions and he have to open 50 boxes jop and the user have to click 50 times in the ok button, since the dialog box does not close itself.

the ideal (in my opinion clear) would be to have a label that informs what is happening at the moment and this label is changing, for this is necessary for the block that changes that label to be in a Thread for the application itself does not get stuck until the completion. Or a progressbar.. Anyway, it goes from your way of implementing.

The following are examples or attempts by him to explain how he could update real-time information in which it occurs:

  • Considerations 1:

    That one jButton1ActionPerformed() is being pressed right after the user selects some type in the combobox, so I assume the jedpAtualizados will be filled in with information received from client.get(idTipio) and after that the combobox will return to index -1 and soon at the end a message of completion.

  • Considerations 2:

    If here’s the problem, if that get is what you want to do a real-time update, go some other considerations: That one get(idTipo) is being called only once. Soon it will run only once and will return a String by all the indications. This String we do not know whether it is big or small. Whether it will be quick return or not. So that this jedAtualizados is actually filled according to the while loop of the method client.get(idTipo), so this one jedAtualizados has to be filled in there. For this it is important that the jedAtualizados is Static to be accessed elsewhere OR that you pass Jed as parameter in the client get.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        int idTipo = cmbTipos.getSelectedIndex() + 1; //obtem um id
        if (idTipo != -1)//verifica se algum item foi selecionado
        {
            ApiFipe.GetsMarcas client = new ApiFipe.GetsMarcas(); //instancia um client

            /* Leia considerações 1 */
            /* Leia Considerações 2*/
            jedpAtualizados.setContentType("text/html");

            /*linha removida*/
            //jedpAtualizados.setText(client.Get(idTipo));

            /*Linhas adicionadas para não deixar o JFrame atual ficar travado*/
            new Thread(() -> {
                //get corrigido para minusculo
                client.get(idTipo,jedpAtualizados); //Nesse contexto o próprio get já esta utilizando o jed para concatenar
                cmbTipos.setSelectedIndex(-1);
                JOptionPane.showMessageDialog(null, "Categoria atualizada com sucesso!");
            }).start();
        }
    }
  • Considerations 3:

Already in office client.get(idTipo) we have an empty string that will receive the response from the API. Inside the while loop, we concatenate only numbers. I imagine the return of this string would be something like 123248579875321 (example only)... Anyway just numbers. If this is the information you want to appear in jedAtualizados then just inside that while you add these values to the jedAtualizados.

private void get(int idTipo, JEditorPane jedpAtualizados) {
        /* leia considerações 3 */
        //recebe dados de uma api na variavel 'dadosdaapi'
        while (dadosdaapi.next()) {
            //salva esses dados em um banco de dados
            //aqui deve existir a criação desse objeto 'objdedados'

            /*Concatena as informações no jed*/
            jedpAtualizados.setText(jedpAtualizados.getText() + Integer.toString(objdedados.getCodigo());
        }
    }
  • Final considerations:

I see no real advantage in doing this, I just wanted to illustrate that the use of Threads allows component editing without leaving the JFrame current locked. There are no advantages since the return of the API is all coming in a single request, that is, the delay itself is in the request. The loop while will go through existing information and will be completed very fast, IE, will fill the jepAtualizados very fast, so as to see almost no difference at all.

Browser other questions tagged

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