Txt displays duplicate information

0

What this application does: the user has to choose the right answer to the question. I just put a question for now. Once you have save the answer (this is within a .txt) it can see result .

And here's the problem: by clicking on see result, it shows everything right (the first time it shows null, I still can not fix it) . so I close the results window with the close result button appears and disappears with setVisible , but if I click see result > again, it doubles the values on the screen , but only on the screen, everything is saved in txt. I wanted the user to click how many times he wanted the View result button and only appear the errors and correct answers without duplicating the values on the screen.

IfIclickonseeresult3times:

howisitsavedintxt(allright)

packagevisao;importjavax.swing.JFrame;importjavax.swing.JPanel;importjavax.swing.ButtonGroup;importjavax.swing.JButton;importjavax.swing.JLabel;importjavax.swing.JRadioButton;publicclassTelaPainelextendsJFrame{privateJPanelcontentPane;privateJButtonbtVerResultado;privateJButtonbtFecharResultado;privateJButtonbtSalvarRespostas;privateButtonGroupgrupo;privateJRadioButtonradioDois;privateJRadioButtonradioUm;publicTelaPainel(){setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setBounds(100,100,450,300);contentPane=newJPanel();contentPane.setLayout(null);setContentPane(contentPane);btVerResultado=newJButton("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());
}
}
    
asked by anonymous 29.12.2017 / 16:29

1 answer

3

TL; DR

The reason for "doubling" the rows is because you are using the append() method in JTexArea , and this method will concatenate new strings into existing ones. Change by%% method that concatenation will no longer occur.

The code presented, although already an executable example, has other errors that could not go unnoticed and are linked, even indirectly, to the problem of the question, so it is worth pointing out and showing how I corrected them.

Here are the only two classes I've changed:

In class setText() :

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:

  • I created the ControleTelaPainel method so that you can use it to read the results of the text file and load them into the countQtdErroPlanificacao class. In the example, I'm just reading the first line, but if you're going to deploy multiple users by responding to the questionnaire, you'll just have to loop through this method to retrieve all lines;

  • li>
  • Within% if_%, I changed 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);
    }
    

Since you used counters to store right and wrong answers, this is the responsibility of the countQtdAcertoPlanificacao class. Instead of counters and increments, simply retrieve the value of the getters and add with one, passing this result to the setters.

  • no if DadoResultadoAluno changed 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 class lerResultados() is that stores the results, we will only recover those values. Here is also the origin of the initial error of the question, changing to DadoResultadoAluno , the problem no longer occurs. The AlunoArquivo method is no longer required and does not exist with these changes above, as I will explain below.

In class ArqConfig :

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 got much leaner, and the changes I made were:

  • I have created a method for you to check if the file exists, so you are free to have to be capturing exceptions to check this;

  • In methods (e.getSource() == tp.getBtSalvarRespostas() and DadoResultadoAluno , I added the above verification, which eliminates capturing (e.getSource() == tp.getBtVerResultado()) ;

  • In the DadoResultadoAluno method, 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 is lost for the first time. Only by removing setText() this problem is solved;

  • As you may have noticed, the responsibility to persist is only of class AlunoArquivo.mostrar(ArqConfig); , no need of other classes nor know the path to the file, so some signatures in this class the path has been removed as parameter;

  • With the changes we made to the previous class, the AlunoArquivo , Read() , and Write() methods have become obsolete and unnecessary since you already have the FileNotFoundException method to read the file lines and who reads the results is the class explained above.

With these "small changes, your code is more organized, apart from having separate responsibilities for each class, but there are other things that can improve, but not directly or indirectly linked to the problem.     

29.12.2017 / 20:05