Popular jComboBox com Valores de um Arquivo TXT

8 respostas
pzanetti631

Como eu faço para popular uma jComboBox com valores trazidos de um arquivo texto?

Tentei este código

File arquivo = new File("C:\\Paulo\\Arquivo.txt");
        try {
            FileReader fr = new FileReader(arquivo);
            jComboBox1.removeAllItems();
            BufferedReader br = new BufferedReader(fr);
            
            for (String linha = br.readLine(); linha != null; linha = br.readLine()) {  
                jComboBox1.addItem(linha);    
            } 

            br.close();
            
        } catch (IOException e) {
            System.err.printf("Erro na leitura do Arquivo: %s.\n", 
                    e.getMessage());
        }

mas não consegui…

8 Respostas

E

Troque isto aqui (que é um loop infinito: )

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

por:

for (String linha = br.readLine(); linha != null; linha = br.readLine()) {
                jComboBox1.addItem(linha);  
            }
pzanetti631

Troquei, mas não funcionou…

Você teria um código similar, que funcione?

E

Uai, que eu saiba você tem de fazer isso mesmo que você fez. Você checou se não houve algum problema para ler o arquivo, por exemplo?

pzanetti631

Esse mesmo código funciona quando executado via linha de comando…

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class LeArquivo {
    public static void main(String[] args) {
        File arquivo = new File("C:\\Paulo\\Arquivo.txt");
        System.out.printf("\nConteúdo do Arquivo:\n");
        System.out.println();
        
        try {
            FileReader fr = new FileReader(arquivo);
            BufferedReader br = new BufferedReader(fr);
           
            for (String linha = br.readLine(); linha != null; linha = br.readLine()) {  
                System.out.printf("%s\n", linha);
            }

            fr.close();
            
        } catch (IOException e) {
            System.err.printf("Erro na leitura do Arquivo: %s.\n", 
                    e.getMessage());
        }

        System.out.println();
    }
}

Em tempo: os componentes SWING quem gerou pra mim foi o Netbeans…

dudu_sps

voce está chamando o metodo para popular, depois de ter carregado os componentes?

pzanetti631

Não, eu estou “batendo cabeça” com o Swing, que não é minha praia…

Você poderia me dar um exemplo de como fazer isso?

dudu_sps

se voce tiver fazendo a leitura logo ao abrir a tela…
voce tem que chamar o metodo depois do construtor

public class Classe(){

initialize();

metodoCarregar();

}

mais ou menos assim

JavaDreams

Olá amigo, eu alterei seu código aqui e deu certo.
Segue abaixo um exemplo de como fazer para funcionar:

package LeArquivo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class NewJFrame extends javax.swing.JFrame {

     ArrayList<String> lista = new ArrayList();
    
    public NewJFrame() {
        initComponents();
        
        File arquivo = new File("C:\\Paulo\\Arquivo.txt");  
        
        try {  
                FileReader fr = new FileReader(arquivo);  
                BufferedReader br = new BufferedReader(fr);  
                String linha = br.readLine();
                
                while(linha != null){
            
                    jComboBox1.addItem(linha);
                    linha = br.readLine();

                }  
      
                fr.close();  
                  
            } catch (IOException e) {  
                System.err.printf("Erro na leitura do Arquivo: %s.\n",   
                        e.getMessage());  
            }  
      
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jComboBox1 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(140, 140, 140)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(232, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(119, 119, 119)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(161, Short.MAX_VALUE))
        );

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

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        
           
        
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JComboBox jComboBox1;
    // End of variables declaration
}


Meu arquivo txt eu criei no diretório
C:\Paulo\Arquivo.txt

e coloquei dentro dele 3 linhas assim:
Carlos
Joao
Maria

No meu aqui rodou numa boa
e deixei o print de tela em anexo para ajudar
a ver tudo que rodou perfeito.

Abraço e se precisar posta aí que a gente ajuda.


Criado 2 de agosto de 2013
Ultima resposta 20 de ago. de 2013
Respostas 8
Participantes 4