ArrayList sobrescrevendo os dados [Resolvido]

6 respostas
xandelol

Olá galera, tudo bem?
Eu estou tentando passar os dados de um arquivo .txt para um jTable, mas os dados saem repetidos.
Exemplo: arquivo .txt

Ale gs123 123 out 12,30 Alexan gs213 123 look 13,20 Alexandre gs321 123 Outlook 25,50
jTable

Alexandre gs321 123 Outlook 25,50 Alexandre gs321 123 Outlook 25,50 Alexandre gs321 123 Outlook 25,50

Alguém pode me ajudar?

Esse é método onde eu pego os dados…

public void Scan(){
        Scanner scan = null;
        try {
            scan = new Scanner(new File("path do meu arquivo"));
            while (scan.hasNextLine()) {
                //Lê a linha com o nextLine e a divide em colunas com o split
                String[] campos = scan.nextLine().split("/");
                dadostbl.add(new TableDados(campos[0], campos[1] ,Integer.parseInt(campos[2]), campos[3], Double.parseDouble(campos[4].replaceAll(",","."))));
                novosfunc=true;
            }
        }
        catch (Exception e) {
            novosfunc=false;
            throw new RuntimeException(e);
        }
        finally {
            scan.close();
        }
    }

E essa é a classe onde fica as variáveis…

public class TableDados {
    private String nomefunc;
    private String gs;
    private int cc;
    private String atividade;
    private double valor;
    
    public TableDados(String nomefunc, String gs, int cc, String atividade, double valor){
        this.nomefunc = nomefunc;
        this.gs = gs;
        this.cc = cc;
        this.atividade = atividade;
        this.valor = valor;
    }
    
    public String getNomefunc(){
        return nomefunc;
    }
    
    public String getGS(){
        return gs;
    }
    
    public int getCC(){
        return cc;
    }
    
    public String getAtividade(){
        return atividade;
    }
    
    public double getValor(){
        return valor;
    }
}

6 Respostas

A

Vê se isso pode te ajudar…

try { 
			String filePath = "arquivo.txt";  
			BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
			String str;
			while ((str = in.readLine()) != null) {
				String[] arr = str.split(" ");
				System.out.println(arr[0]+" "+arr[1]+" "+arr[2]+" "+arr[3]+" "+arr[4]);
			}  
			in.close();  
		} catch (Exception e) {  
			System.out.println("Erro ao ler arquivo de texto " + e.toString());  
		}
xandelol

Valeu a ajuda akah, mas não resolveu…
O ArrayList deve ter algo contra mim… :roll:
kkkkkkkkkkkkkk

A

cola seu frame e as classes que ta usando…

xandelol

Tá ai…

public class NovoCustoTableModelFrame extends JFrame {

    private JTable tblDados;
    private NovoCustoTableModel tableModel;
    static Collection<TableDados> collection;    
    static String[] nfunc = new String[3000];
    static String[] gsfunc = new String[3000];
    static int[] ccfunc = new int[3000];
    static String[] atvfunc = new String[3000];
    static double[] valorfunc = new double[3000];
    static int i, numLinhaslog=0, numfunc=0;
    static boolean leulog=false, novosfunc=false;
    static List<TableDados> dadostbl = new ArrayList<TableDados>();
    static TableDados[] tbledados = new TableDados[3000];

    public NovoCustoTableModelFrame() {
        super("Tabela de Custos");
        initialize();        
        setLocationRelativeTo(null);
        
        Image imagemTitulo = Toolkit.getDefaultToolkit().getImage(getClass().getResource("ZF-Transmission.jpg"));
        this.setIconImage(imagemTitulo);
        
        setDefaultCloseOperation(this.HIDE_ON_CLOSE);
    }
    
    private void initialize() {
        dadostbl.clear();
        Scan();
        setSize(800, 500);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        getContentPane().add(getTblDados());
        getContentPane().add(new JScrollPane(getTblDados()));        
    }
   
    private JTable getTblDados() {
        if (tblDados == null) {
            tblDados = new JTable();
            tblDados.setModel(getTableModel());
        }
        return tblDados;
    }

    private NovoCustoTableModel getTableModel() {
        if (tableModel == null) {
            tableModel = new NovoCustoTableModel(criaDados());
        }
        return tableModel;
    }

    public List<DadosNC> criaDados() {
        collection = dadostbl;
        List<DadosNC> dados = new ArrayList<DadosNC>();
        for (int j=0; j<numfunc; j++) {
            DadosNC dadosnc = new DadosNC();
            dadosnc.setNomefunc(tbledados[j].getNomefunc());
            dadosnc.setGS(tbledados[j].getGS());
            dadosnc.setCC(tbledados[j].getCC());
            dadosnc.setAtividade(tbledados[j].getAtividade());
            dadosnc.setValor(tbledados[j].getValor());
            dados.add(dadosnc);
        }
        return dados;
    }

    @SuppressWarnings("unchecked")

    public static void main(String args[]) {

        /*
         * 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(NovoCustoTableModelFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NovoCustoTableModelFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NovoCustoTableModelFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NovoCustoTableModelFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new NovoCustoTableModelFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    // End of variables declaration

    public void Scan(){
        try {
            int t=0;
            String filePath = "path do arquivo";    
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));  
            String str;  
            while ((str = in.readLine()) != null) {  
                String[] arr = str.split("/");  
                tbledados[t] = new TableDados();
                tbledados[t].setNomefunc(arr[0]);
                tbledados[t].setGS(arr[1]);
                tbledados[t].setCC(Integer.parseInt(arr[2]));
                tbledados[t].setAtividade(arr[3]);
                tbledados[t].setValor(Double.parseDouble(arr[4].replaceAll(",", ".")));
                t++;
            }    
            in.close();
            numfunc = t;
            for (int j = 0; j < t; j++) {
                System.out.print(tbledados[j].getNomefunc()+" ");
                System.out.print(tbledados[j].getGS()+" ");
                System.out.print(tbledados[j].getCC()+" ");
                System.out.print(tbledados[j].getAtividade()+" ");
                System.out.println(tbledados[j].getValor());
            }
        } 
        catch (Exception e) {    
            System.out.println("Erro ao ler arquivo de texto " + e.toString());    
        }  
}

e essa…

public class DadosNC {
    static String nomefunc;
    static String gs;
    static int cc;
    static String atividade;
    static double valor;
    
    public String getNomefunc(){
        return nomefunc;
    }
    
    public String getGS(){
        return gs;
    }
    
    public int getCC(){
        return cc;
    }
    
    public String getAtividade(){
        return atividade;
    }
    
    public double getValor(){
        return valor;
    }

    public void setNomefunc(String nomefunc){
        this.nomefunc=nomefunc;
    }
    
    public void setGS(String gs){
        this.gs=gs;
    }
    
    public void setCC(int cc){
        this.cc=cc;
    }
    
    public void setAtividade(String atividade){
        this.atividade=atividade;
    }
    
    public void setValor(double valor){
        this.valor=valor;
    }
}

E a classe TableDados…

public class TableDados {
    private String nomefunc;
    private String gs;
    private int cc;
    private String atividade;
    private double valor;

    public void setNomefunc(String nomefunc){
        this.nomefunc=nomefunc;
    }
    
    public void setGS(String gs){
        this.gs=gs;
    }
    
    public void setCC(int cc){
        this.cc=cc;
    }
    
    public void setAtividade(String atividade){
        this.atividade=atividade;
    }
    
    public void setValor(double valor){
        this.valor=valor;
    }

    public String getNomefunc(){
        return nomefunc;
    }
    
    public String getGS(){
        return gs;
    }
    
    public int getCC(){
        return cc;
    }
    
    public String getAtividade(){
        return atividade;
    }
    
    public double getValor(){
        return valor;
    }
xandelol

up++;

xandelol

Consegui resolver o problema…
Eu tinha declarado as variáveis da minha classe DadosNC, como [color=blue] static [/color].
Pura bobice minha! :mrgreen:

Obrigado a quem me ajudou!

Criado 22 de março de 2013
Ultima resposta 26 de mar. de 2013
Respostas 6
Participantes 2