Txt displays duplicate information

Asked

Viewed 115 times

0

What this application does: the user has to choose the right answer to the question. I have only put a question for now. After save the answer (is inside a . txt) he can see result.

And there’s the problem: by clicking on the result, it shows everything right (The first time, it shows null, I still can’t fix it). then I close the results window with the button close result (that appears and disappears with the setVisible) , only if I click see result again, he duplicate the values on the screen , but only on the screen, txt is saved all right. I wish the user could click as many times as he wanted on boot see result and only errors and correct questions appeared, without duplicating the values on the screen.

tela inicial. sempre que o usuário for jogar, ele pode ver seu desempenho, por exemplo: da primeira vez que eu joguei eu fiz X acerto e Y erros, da segunda ...

if I click see result 3 times:

inserir a descrição da imagem aqui

how is saved in txt (all right)

inserir a descrição da imagem aqui

package visao;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JRadioButton;

public class TelaPainel extends JFrame {

private JPanel contentPane;
private JButton btVerResultado;
private JButton btFecharResultado;
private JButton btSalvarRespostas;
private ButtonGroup grupo;
private JRadioButton radioDois;
private JRadioButton radioUm;

public TelaPainel() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setLayout(null);
    setContentPane(contentPane);

    btVerResultado = new JButton("ver resultado");
    btVerResultado.setBounds(236, 156, 121, 23);
    contentPane.add(btVerResultado);

    btFecharResultado = new JButton("fechar resultado");
    btFecharResultado.setBounds(236, 156, 121, 23);
    btFecharResultado.setVisible(false);
    contentPane.add(btFecharResultado);

    btSalvarRespostas = new JButton("Salvar respostas");
    btSalvarRespostas.setBounds(22, 156, 131, 23);
    contentPane.add(btSalvarRespostas);

    JLabel lblQueAnimal = new JLabel("Que animal \u00E9 esse?");
    lblQueAnimal.setBounds(22, 45, 113, 14);
    contentPane.add(lblQueAnimal);

    radioUm = new JRadioButton("Cachorro");
    radioUm.setBounds(26, 75, 109, 23);
    contentPane.add(radioUm);

    radioDois = new JRadioButton("Gato");
    radioDois.setBounds(26, 113, 109, 23);
    contentPane.add(radioDois);

    grupo = new ButtonGroup();
    grupo.add(radioUm);
    grupo.add(radioDois);
    setVisible(true);
}

public JButton getBtVerResultado() {
    return btVerResultado;
}

public void setBtVerResultado(JButton brVerResultado) {
    this.btVerResultado = brVerResultado;
}

public JButton getBtFecharResultado() {
    return btFecharResultado;
}

public void setBtFecharResultado(JButton btFecharResultado) {
    this.btFecharResultado = btFecharResultado;
}

public JButton getBtSalvarRespostas() {
    return btSalvarRespostas;
}

public JRadioButton getRadioDois() {
    return radioDois;
}

public void setRadioDois(JRadioButton radioDois) {
    this.radioDois = radioDois;
}

public JRadioButton getRadioUm() {
    return radioUm;
}

public void setRadioUm(JRadioButton radioUm) {
    this.radioUm = radioUm;
}

public void setBtSalvarRespostas(JButton btSalvarRespostas) {
    this.btSalvarRespostas = btSalvarRespostas;
}
}

package visao;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;

public class TelaExibir extends JFrame {

private JPanel contentPane;
private JTextArea textArea;

public TelaExibir() {
    setFocusable(true);
    setUndecorated(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 285, 164);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    textArea = new JTextArea();
    textArea.setLayout(null);
    textArea.setBounds(0, 0, 200, 100);
    JScrollPane scroll = new JScrollPane(textArea);
    scroll.setBounds(0, 0, 285, 164);
    contentPane.add(scroll);

    setLocationRelativeTo(null);
    setLocationRelativeTo(null);
    setResizable(false);
}

public JTextArea getTextArea() {
    return textArea;
}

public void setTextArea(JTextArea textArea) {
    this.textArea = textArea;
}
}

package modelo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class AlunoArquivo {

public static File arquivo = new File("exibir.txt");
static DadoResultadoAluno dra = new DadoResultadoAluno();
private static String c1;
private static String c2;

public static List<String> Read(String Caminho) {
    List<String> conteudo = new ArrayList<>();

    try {
        FileReader arq = new FileReader(arquivo);
        BufferedReader lerArq = new BufferedReader(arq);
        String linha = "";
        try {
            linha = lerArq.readLine();
            while (linha != null) {
                conteudo.add(linha);
                linha = lerArq.readLine();
            }
            arq.close();
            return conteudo;
        } catch (IOException ex) {
            System.out.println("Erro: Não foi possível ler o arquivo!");
        }
    } catch (FileNotFoundException ex) {
        System.out.println("Erro: Arquivo não encontrado!");
    }
    return null;
}


public static boolean Write(String Caminho,String Texto){
    try {
        if (!arquivo.exists()) {
            arquivo.createNewFile();
            System.out.println("not");
        } else {
            System.out.println("Yes");
            FileWriter arq = new FileWriter(arquivo, true);
            PrintWriter gravarArq = new PrintWriter(arq);
            gravarArq.println(Texto);
            gravarArq.close();
        }
        return true;
    }catch(IOException e){
        System.out.println(e.getMessage());
        return false;
    }
}


public static void salvar(int countQtdAcertoPlanificacao, int countQtdErroPlanificacao, String ArqConfig){

    dra.setQtdAcertoPlanificacao(countQtdAcertoPlanificacao);
    dra.setQtdErroPlanificacao(countQtdErroPlanificacao);

    String print = dra.getQtdAcertoPlanificacao() + ";" + dra.getQtdErroPlanificacao();
    System.out.println("ultimo cont: "+countQtdErroPlanificacao + "");

    if (AlunoArquivo.Write(ArqConfig, print)) {
        System.out.println("Arquivo salvo com sucesso!");
    } else {
        System.out.println("Erro ao salvar o arquivo!");
    }
}

public static void mostrar(String ArqConfig){
    List<String> conteudo = AlunoArquivo.Read(ArqConfig);

    for(String linha : conteudo) {
        c1 = linha.split(";")[0];
        c2 = linha.split(";")[1];
    }
}

public static String getC1() {
    return c1;
}

public static String getC2() {
    return c2;
}
}


package modelo;

public class DadoResultadoAluno {

private int qtdAcertoPlanificacao = 0;
private int qtdErroPlanificacao = 0;

public int getQtdAcertoPlanificacao() {
    return qtdAcertoPlanificacao;
}

public void setQtdAcertoPlanificacao(int qtdAcertoPlanificacao) {
    this.qtdAcertoPlanificacao = qtdAcertoPlanificacao;
}

public int getQtdErroPlanificacao() {
    return qtdErroPlanificacao;
}

public void setQtdErroPlanificacao(int qtdErroPlanificacao) {
    this.qtdErroPlanificacao = qtdErroPlanificacao;
}
}


package controle;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import modelo.AlunoArquivo;
import modelo.DadoResultadoAluno;
import visao.TelaExibir;
import visao.TelaPainel;

public class ControleTelaPainel implements ActionListener{

private static Integer countQtdErroPlanificacao = 0;
private static Integer countQtdAcertoPlanificacao = 0;
private String ArqConfig = "exibir.txt";
private DadoResultadoAluno dra;
private AlunoArquivo aa = new AlunoArquivo();
TelaExibir exibir = new TelaExibir();
private TelaPainel tp;

public ControleTelaPainel(TelaPainel tp) {
    this.tp = tp;
    this.tp.getBtFecharResultado().addActionListener(this);
    this.tp.getBtVerResultado().addActionListener(this);
    this.tp.getBtSalvarRespostas().addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent e) {

    if(e.getSource()== tp.getBtFecharResultado()){

        this.tp.getBtVerResultado().setVisible(true);
        this.tp.getBtFecharResultado().setVisible(false);

        exibir.setVisible(false);
    }

    else if(e.getSource() == tp.getBtSalvarRespostas()){

        if(tp.getRadioUm().isSelected()){
            countQtdAcertoPlanificacao++;
        }else if(tp.getRadioDois().isSelected()){
            countQtdErroPlanificacao++;
        }
        AlunoArquivo.salvar(countQtdAcertoPlanificacao, countQtdErroPlanificacao, ArqConfig);
    }

    else if(e.getSource()== tp.getBtVerResultado()){

        AlunoArquivo.mostrar(ArqConfig);

        exibir.getTextArea().append("Você fez " + AlunoArquivo.getC1() + " acertos" + " e " + AlunoArquivo.getC2() + " tentativas erradas");
        exibir.getTextArea().append("\n\n");

        exibir.setVisible(true);
        this.tp.getBtFecharResultado().setVisible(true);
        this.tp.getBtVerResultado().setVisible(false);
    }
}
}

package controle;

import visao.TelaPainel;
public class Main {

public static void main(String[] args) {
    ControleTelaPainel ctp = new ControleTelaPainel(new TelaPainel());
}
}
  • 1

    Where the class Imports??

  • format the classes as well, by clicking on {}

  • I have placed the Imports!

  • 1

    Gabriella, you did not find any errors to suggest in the other answer, I suggest you go back to it and read carefully, because you keep keeping the wrong codes that I already corrected in the answer: https://answall.com/a/263720/28595

  • And I remember, but now it’s different. when I try to do it that way, the messages duplicate

  • The null error you mention I have already corrected in the other code, reread the answer and you will see that I comment on it.

  • ok, but in the other answer, by double-clicking the display button, it duplicates the same values that are happening in this code. there was also not corrected

  • Because the problem there was another.

  • but null, I just mentioned so you wouldn’t think that the main fluff was this. The main focus is the fact of duplicating the messages in the display. null I try to solve later

  • Without resolving null, the code is not executable.

  • the first time in fact it does not but when it rotates the second time, already it is

  • Here it is not running at all. I suggest you edit because something must have been missing.

  • I’ll take a look here, but these prints I took of it working. I’ll delete the txt and see from scratch

  • error here, if I try to see answer first, after I saved twice, ie I answer twice , good wheel

  • 1

    So your code has more errors than the question, which prevent you from properly simulating the problem.

Show 11 more comments

1 answer

3


TL;DR

The reason you "duplicate" the lines is because you are using the method append() in the JTexArea, and this method concatenates new strings into existing ones. Switch to the method setText() that concatenation will no longer occur.


The code presented, although already an executable example, has other errors that could not go unnoticed and that are linked, even indirectly, to the question problem, so it is worth highlighting them and show how to correct them.

Here are the only two classes I’ve changed:

In class ControleTelaPainel:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ControleTelaPainel implements ActionListener {

    private DadoResultadoAluno dra = new DadoResultadoAluno();
    TelaExibir exibir = new TelaExibir();
    private TelaPainel tp;

    public ControleTelaPainel(TelaPainel tp) {
        this.tp = tp;
        this.tp.getBtFecharResultado().addActionListener(this);
        this.tp.getBtVerResultado().addActionListener(this);
        this.tp.getBtSalvarRespostas().addActionListener(this);
        lerResultados(0);

    }

    public void lerResultados(int indice) {
        List<String> linhas =  AlunoArquivo.Read();

        if(linhas == null)
            return;

        dra.setQtdAcertoPlanificacao(Integer.parseInt(linhas.get(indice).split(";")[0]));
        dra.setQtdErroPlanificacao((Integer.parseInt(linhas.get(indice).split(";")[1])));
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == tp.getBtFecharResultado()) {

            this.tp.getBtVerResultado().setVisible(true);
            this.tp.getBtFecharResultado().setVisible(false);

            exibir.setVisible(false);
        }

        else if (e.getSource() == tp.getBtSalvarRespostas()) {

            if (tp.getRadioUm().isSelected()) {
                dra.setQtdAcertoPlanificacao(dra.getQtdAcertoPlanificacao() + 1);
            } else if (tp.getRadioDois().isSelected()) {
                dra.setQtdErroPlanificacao(dra.getQtdErroPlanificacao() + 1);
            }
            AlunoArquivo.salvar(dra);
        }

        else if (e.getSource() == tp.getBtVerResultado()) {

            exibir.getTextArea().setText("Você fez " + dra.getQtdAcertoPlanificacao() + " acertos" + " e "
                    + dra.getQtdErroPlanificacao() + " tentativas erradas");

            exibir.setVisible(true);
            this.tp.getBtFecharResultado().setVisible(true);
            this.tp.getBtVerResultado().setVisible(false);

        }
    }
}

I’ve made the following changes:

  • the variables countQtdErroPlanificacao and countQtdAcertoPlanificacao are not necessary, given that their class DadoResultadoAluno already has the finality of storing the errors and correctness of the questions;

  • created the method lerResultados() so that you can use it to read the results of the text file and load them into the class DadoResultadoAluno. In the example, I’m just reading the first line, but if you’re going to implement multiple users answering the questionnaire, just loop it with this method to recover all the lines;

  • bearing in mind that the class AlunoArquivo is that you need to make persistence in the text file, the variable ArqConfig in this context is unnecessary and even violates the principle of class responsibility;

  • within the if (e.getSource() == tp.getBtSalvarRespostas(), I switched to:

    else if (e.getSource() == tp.getBtSalvarRespostas()) {
    
        if (tp.getRadioUm().isSelected()) {
            dra.setQtdAcertoPlanificacao(dra.getQtdAcertoPlanificacao() + 1);
        } else if (tp.getRadioDois().isSelected()) {
            dra.setQtdErroPlanificacao(dra.getQtdErroPlanificacao() + 1);
        }
        AlunoArquivo.salvar(dra);
    }
    

once you used accountants to store right and wrong answers, when that is the responsibility of the class DadoResultadoAluno. Instead of counters and increments, just retrieve the value of the getters and add one, passing this result to the setters.

  • in the if (e.getSource() == tp.getBtVerResultado()) I switched to:

    else if (e.getSource() == tp.getBtVerResultado()) {
    
        exibir.getTextArea().setText("Você fez " + dra.getQtdAcertoPlanificacao() + " acertos" + " e "
                + dra.getQtdErroPlanificacao() + " tentativas erradas");
    
        exibir.setVisible(true);
        this.tp.getBtFecharResultado().setVisible(true);
        this.tp.getBtVerResultado().setVisible(false);
    
    }
    

since, as already mentioned above, the DadoResultadoAluno is that stores the results, we will only recover from it those values. Here is also the origin of the initial error of the question, changing to setText() the problem no longer occurs. The method AlunoArquivo.mostrar(ArqConfig); is no longer necessary and does not exist with these amendments above, as I will explain below.


In class AlunoArquivo:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class AlunoArquivo {

    public static File arquivo = new File("exibir.txt");

    public static List<String> Read(String Caminho) {
        List<String> conteudo = new ArrayList<>();

        try {
            FileReader arq = new FileReader(arquivo);
            BufferedReader lerArq = new BufferedReader(arq);
            String linha = "";
            try {
                while (linha != null) {
                    conteudo.add(linha);
                    linha = lerArq.readLine();
                }
                arq.close();
                return conteudo;
            } catch (IOException ex) {
                System.out.println("Erro: Não foi possível ler o arquivo!");
            }
        } catch (FileNotFoundException ex) {
            System.out.println("Erro: Arquivo não encontrado!");
        }
        return null;
    }

    public static boolean Write(String Texto) {
        try {
            if (!arquivoExiste()) {
                arquivo.createNewFile();
                System.out.println("not");
            } 

            System.out.println("Yes");
            FileWriter arq = new FileWriter(arquivo, true);
            PrintWriter gravarArq = new PrintWriter(arq);
            gravarArq.println(Texto);
            gravarArq.close();

            return true;
        } catch (IOException e) {
            System.out.println(e.getMessage());
            return false;
        }
    }

    public static void salvar(DadoResultadoAluno dra) {

        String print = dra.getQtdAcertoPlanificacao() + ";" + dra.getQtdErroPlanificacao();

        if (AlunoArquivo.Write(print)) {
            System.out.println("Arquivo salvo com sucesso!");
        } else {
            System.out.println("Erro ao salvar o arquivo!");
        }
    }

    public static boolean arquivoExiste() {
        return arquivo.exists();
    }
}

It was much leaner, and the changes I made were:

  • I created a method for you to check if the file exists, so you’re free to keep capturing exceptions to check it;

  • in the methods Read() and Write(), i added the above mentioned check, which eliminates capturing the FileNotFoundException;

  • in the method Write(), When checking if a file exists, you create it but do not save the result. This causes the file to be created empty, and the saved result for the first time to be lost. Just by removing the else this problem is solved;

  • in the method salvar()I removed the redundancies I had with those two counters we removed in the other class, and now just pass an instance of DadoResultadoAluno since it is she who saves the results;

  • as you may have noticed, the responsibility to persist is only of the class AlunoArquivo, no need for other classes or knowing the path to the file, so some signatures in this class the path has been removed as parameter;

  • with the changes we made in the previous class, the method mostrar(), getC1() and getC2() have become obsolete and unnecessary, as you already have the method Read() to read the lines of the file and who reads the results is the class explained earlier.


With these "small changes, your code is more organized, and we have separate responsibilities for each class. But there are other things that can be improved, but it is not directly or indirectly linked to the problem.

  • Correct! Thank you very much

Browser other questions tagged

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