How to use Jprogressbar in Arraylist comparison classes?

Asked

Viewed 228 times

0

I have a class that compares two ArrayList, one with information added by the user and the other with database query.

After the query is done, I send this object to another class that performs the writing of this data in a file. I would like, as long as these checks are carried out, to show a JProgressBar for the user not to have the impression that the system is locked.

public ArrayList<ModeloCadastroTerceiro> verificaCodigoTerceiro(ArrayList<ModeloCadastroTerceiro> modelo) {

    ConectaBanco conecta = new ConectaBanco();

  conecta.conexao();
  StringBuilder str_busca = new StringBuilder(); 

    ArrayList<ModeloCadastroTerceiro> modeloRetorno = new ArrayList<>();

    ModeloCadastroTerceiro mod;

    str_busca.append('(');
    for (ModeloCadastroTerceiro modelo1 : modelo) {
        str_busca.append("'");
        str_busca.append(modelo1.getCpfTerceiro());
        str_busca.append("'");
        str_busca.append(',');
    }

    str_busca.deleteCharAt((str_busca.toString().length() - 1));

    str_busca.append(')');

    String busca = String.valueOf(str_busca);

    conecta.executaSQL("select * from cadastro_terceiros where cpf_cnpj_terceiro in" + busca);

    try {
        conecta.rs.first();

        do {
            mod = new ModeloCadastroTerceiro();
            mod.setCodTerceiro(conecta.rs.getInt("id_prosoft_terceiro"));
            mod.setCpfTerceiro(conecta.rs.getString("cpf_cnpj_terceiro"));
            modeloRetorno.add(mod);
        } while (conecta.rs.next());

    } catch (SQLException ex) {
        if (ex.getErrorCode() == 0) {

        } else {
            Logger.getLogger(RecuperaInformacaoBanco.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

   ArrayList<ModeloCadastroTerceiro> fim = new ArrayList<>();
    ModeloCadastroTerceiro modFim;

    for (ModeloCadastroTerceiro mod1 : modelo) {

        boolean flag = false;//usada para marcar terceiro não encontrado

        for (ModeloCadastroTerceiro te1 : modeloRetorno) {

            if (mod1.getCpfTerceiro().equals(te1.getCpfTerceiro())) {
                flag = true;
            }
        }

        if (flag == false) {
            modFim = new ModeloCadastroTerceiro();
            modFim.setCodTerceiro(mod1.getCodTerceiro());
            modFim.setNomeTerceiro(mod1.getNomeTerceiro());
            modFim.setCpfTerceiro(mod1.getCpfTerceiro());
            fim.add(modFim);
        }else{
            System.out.println("TERCEIRO JA CADASTRADO... NÃO SERA IMPORTADO");
        }

    }
    return fim;
}

After that I call the class that writes to the file from a ArrayList

public void escreverNoArquivo(File arquivo, ArrayList<String> texto) {

    FileWriter fw;
    BufferedWriter bw;

    try {

        fw = new FileWriter(arquivo);
        bw = new BufferedWriter(fw);

        // Recupera cada linha do texto e escreve no arquivo
        for (int i = 0; i < texto.size(); i++) {

            // Escreve o texto no arquivo
            bw.write(texto.get(i));
            // Quebra de linha
            bw.newLine();

        }

        bw.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

}

How to make a JProgressBar that shows the progress of this?

  • The press will appear when?

  • The idea is that it appears when writing in the file... Performing the process to generate it from start to finish.

  • Then the progression should follow the progress of the method escreverNoArquivo?

  • Yes that’s right.

1 answer

1


You can make use of the class SwingWorker, placing in it the execution of the method in parallel the execution of the screen.

public void escreverNoArquivo(File arquivo, ArrayList<String> texto) {

    SwingWorker worker = new SwingWorker<Void, Integer>() {

        //executará a ação em uma thread paralela a EDT
        @Override
        protected Void doInBackground() throws Exception {
            FileWriter fw;
            BufferedWriter bw;
            fw = new FileWriter(arquivo);
            bw = new BufferedWriter(fw);

            // Recupera cada linha do texto e escreve no arquivo
            for (int i = 0; i < texto.size(); i++) {
                // Escreve o texto no arquivo
                bw.write(texto.get(i));
                //publica a atualização para a progressbar
                // através do método process(List<type> chunks)
                publish(i);
                // Quebra de linha
                bw.newLine();
            }
            bw.close();
            return null;
        }

        //carrega a progressbar a medida que o publish
        //envia o andamento do doInBackground
        @Override
        protected void process(List<Integer> chunks) {
            int progress = chunks.get(chunks.size() - 1);
            suaProgressBar.setValue(progress);
        }

        @Override
        protected void done() {
            try {
                //captura o retorno do doInBackground
                //mas neste caso, apenas retorna se houver alguma
                //exceção lançado na execução do doInBackground
                get();
                //reseta o progresso, já que a execução terminou
                progressBar.setValue(0);
                JOptionPane.showMessageDialog(progressBar.getParent(),"Terminou!");
            } catch (InterruptedException | ExecutionException ex) {
                ex.printStackTrace();
            }
        }
    };
    //executa a ação anterior.
    worker.execute();
}

Obs.: How it comes to an anonymous class execution, yourProgressBar must be a variable of its screen class, or if it is local, it must be final, otherwise it will not be possible to access it inside the swingWorker, the way it was presented.

If you are interested in learning more about the operation and use of SwingWorker, here are some links that may help:

  • Dude, I know it’s been a long time, but I’ve only been able to test it now. I have a question in the protected void process(List<Integer> Chunks) { int Progress = Chunks.get(Chunks.size() - 1); suaProgressBar.setValue(Progress); }, no time is called and this giving error of "type List does not take Parameters". can you tell me what it can be?

  • @Valdecir Whoever calls the process method is the Publish() method, see that it inserted it into the loop. Now as to the error, see if you have not wrongly imported the class java.awt.List instead of java.util.List.

  • 1

    Guy 2 times in the same day? rsrs Thanks really helped again and so much!

Browser other questions tagged

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