jComboBox does not update data that is already in a . txt

Asked

Viewed 57 times

0

I have a text field to get people’s names and a button that saves these names in a text file, and I also have a jCombobox, but it only shows the data that is inside the txt if I click Save. I wanted the data to appear as soon as I opened the screen, without the need to click save. How to recover these data that are already inside the txt and show in the combobox as soon as the screen is started?

Image: when I open the application is exactly like this. with nothing in the combobox, and you already have data inside the .txt. only when I save a new name is that all the . txt data appears.

quando eu abro a aplicação está exatamente assim. sem nada no combobox, sendo que já tem dados dentro do .txt. somente quando eu salvo um novo nome é que todos os dados do .txt aparecem.

package uploadexemplo;
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;

public class NewJFrame extends javax.swing.JFrame {
    static java.io.File diretorio = new java.io.File("src/arquivo");
    boolean statusDir = diretorio.mkdir();
    public static String nomeDisciplina;
    ArrayList<String> lista = new ArrayList();
    public JButton btnSalvar;
    static FileReader fr;
    static String linha;
    static  BufferedReader br;
    static File arquivo = new File(diretorio, "ArquivoDisciplinas.txt");
    private static javax.swing.JComboBox jComboBox1;
    private static JTextField textField;

    public NewJFrame() {
        try {
            boolean statusArq = arquivo.createNewFile();

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

        initComponents();  
        btnSalvar.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    salvar();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
    }   

    public static boolean Write(String Texto) {
        try {
            if (!arquivoExiste()) {
                arquivo.createNewFile();
            }
            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() throws IOException {
        fr = new FileReader(arquivo);  
        br = new BufferedReader(fr);  
        linha = br.readLine();
        String print = textField.getText() + ";";

        while(linha != null){
            jComboBox1.addItem(linha);
            linha = br.readLine();
        }
        if (NewJFrame.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();
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {
        jComboBox1 = new javax.swing.JComboBox();
        textField = new JTextField();
        textField.setColumns(10);
        btnSalvar = new JButton("Salvar");
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        layout.setHorizontalGroup(
            layout.createParallelGroup(Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(19)
                    .addGroup(layout.createParallelGroup(Alignment.LEADING)
                        .addComponent(jComboBox1, GroupLayout.PREFERRED_SIZE, 149, GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                            .addGap(35)
                            .addComponent(btnSalvar)))
                    .addContainerGap(171, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(23)
                    .addGroup(layout.createParallelGroup(Alignment.BASELINE)
                        .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnSalvar))
                    .addGap(76)
                    .addComponent(jComboBox1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(161, Short.MAX_VALUE))
        );
        getContentPane().setLayout(layout);

        pack();
    }// </editor-fold>
}

1 answer

1


A very simple way to do this is to partially isolate the code present in the method salvar in some other method, for example readText:

private static void readText() throws IOException {
    fr = new FileReader(arquivo);  
    br = new BufferedReader(fr);  
    linha = br.readLine();

    jComboBox1.removeAllItems();

    while(linha != null){
        jComboBox1.addItem(linha);
        linha = br.readLine();
    }

    br.close();
}

This way, you have a method only with the responsibility of reading the file and inserting the items in the combobox.

Obs.: Add the removeAllItems method to avoid duplicating items already present in txt.


Now just call the new method created (readText) in the method salvar after inserting the new line in txt, thus updating the combobox with the new item:

public static void salvar() throws IOException {
    String print = textField.getText() + ";";

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

    //Insere os itens no combobox
    readText();
}

So the previous code keeps working and you have a new method that updates the combobox, so we can also call it in the class constructor, after creating the interface items, because it needs the combobox to already be instantiated:

public NewJFrame() {
    try {
        boolean statusArq = arquivo.createNewFile();

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

    initComponents();

    btnSalvar.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                salvar();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    });

    //Insere os itens no combobox
    try {
        readText();
    } catch (IOException e) {
        e.printStackTrace(); 
    }
}   

With this, when instantiating the Newjframe class, txt is already read and the combobox is created according to the values present in txt.

  • Perfect, Daniel Mendes! Only he is allowing to save two equal names. How do I make him not allow? thanks

  • You could read the txt and check if the name already exists in any line before entering the name of txt, then the rules you said, could compare everything in lowercase for example.

  • I tried it within the readText method, but it didn’t work: while (linha != null) {&#xA; if (linha != print) {&#xA; jComboBox1.addItem(linha);&#xA; linha = br.readLine();&#xA; }&#xA; }

  • But you have to try to do inside the method that saves. Read by what I understand does not save

  • 1

    The method that actually saves the data in txt is Write, so it would be a candidate to gain this validation, if not it would be the saving method.

  • Gee, I couldn’t. But I’m grateful for the previous answer. But if you want to help again, I’m waiting

Show 1 more comment

Browser other questions tagged

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