Ajuda com Collections

Olá…

Eu estou desenvolvendo um sisteminha onde eu manipulo um arquivo .txt, pego as informações necessárias e depois quero colocá-las num JTable…

Abaixo seguem os arquivos:

Carteira.java: arquivo que representa um objeto que eu pego no arquivo .txt.

/**
*

  • @author Adriano
    */
    public class Carteira {

    private String id;
    private String descricao;
    private double valor;
    private int quantidadeDeClientes;

    /** Creates a new instance of Carteira */

    public Carteira()
    {
    }

    public Carteira(String id,String desc,double val,int quant) {

     setId(id);
     setDescricao(desc);
     setValor(val);
     setQuantidadeDeClientes(quant);
    

    }

    public void setId(String id)
    {
    this.id = id;
    }

    public String getId()
    {
    return id;
    }

    public void setDescricao(String desc)
    {
    descricao = desc;
    }

    public String getDescricao()
    {
    return descricao;
    }

    public void setValor(double val)
    {
    valor = val;
    }

    public double getValor()
    {
    return valor;
    }

    public void setQuantidadeDeClientes(int quant)
    {
    quantidadeDeClientes = quant;
    }

    public int getQuantidadeDeClientes()
    {
    return quantidadeDeClientes;
    }

}

ColecaoDeCarteiras.java : arquivo que representa um conjunto de Carteiras q eu uso para fazer a interação com o JTable

import java.util.*;

/**
*

  • @author Adriano
    */
    public class ColecaoDeCarteiras{

    Vector carteiras = new Vector();

    public ColecaoDeCarteiras()
    {
    }

    public void addCarteira(Carteira cart)
    {
    Carteira carteira = new Carteira(cart.getId(),cart.getDescricao(),cart.getValor(),cart.getQuantidadeDeClientes());

     carteiras.add(carteira);
    

    }

    public void addCarteira(String id,String desc,double valor, int quant)
    {
    Carteira carteira = new Carteira(id,desc,valor,quant);

     carteiras.add(carteira);     
    

    }

    public Vector getColecaoDeCarteiras()
    {
    return carteiras;
    }

    public Iterator createIterator()
    {
    return carteiras.iterator();
    }

}

ManipulaTXT.java

import java.util.;
import java.io.
;
import java.text.DecimalFormat;

/**
*

  • @author Adriano
    */
    public class ManipulaTXT {

    private Scanner input;
    private Relatorio rel = new Relatorio();
    private String informacoesInspecao;
    StringTokenizer t1,t2,t3;
    ColecaoDeCarteiras carteiras = new ColecaoDeCarteiras();
    String linhaTXT;
    String aux,aux1;
    double valor;
    StringBuffer auxbf;

    public ManipulaTXT()
    {
    //carteiras = new ColecaoDeCarteiras();
    pegaDadosTXT();
    }

    public void openFile()
    {
    try
    {
    input = new Scanner(new File(“relatorios/relatório.txt”));
    }
    catch(FileNotFoundException erro)
    {
    System.err.println(“Erro na abertura do arquivo.”);
    System.exit(1);
    }
    }

    public void pegaDadosTXT()
    {

         try
         {
     		while(input.hasNext())
     		{
                     if(rel.estaNoCabecalho(input.nextLine()))
                         input.nextLine();				
                     else
                         break;
     		
     				informacoesInspecao = input.nextLine();
    
     		
     				for(int i=0; i<4; i++)
                         input.nextLine();
     	
                     linhaTXT = input.nextLine();
                    
                     while(!rel.linhaEstaVazia(linhaTXT))
                     {
                     
                         Carteira cart1 = new Carteira();
    
                         cart1.setId(linhaTXT.substring(0,4).trim());
                         cart1.setDescricao(linhaTXT.substring(5,46));
                         
                         aux = linhaTXT.substring(48,63); 
                         aux = aux.replace(",",".");
                         aux = aux.trim();
                         t1 = new StringTokenizer(aux);
                         aux = new String();
                         
                         while(t1.hasMoreTokens())
                           aux += t1.nextToken(".");
                         
                         cart1.setValor(Double.parseDouble(aux));
                        
                         cart1.setQuantidadeDeClientes(Integer.parseInt(linhaTXT.substring(63,72).trim()));
          
                         carteiras.addCarteira(cart1);
                         
                         if(linhaTXT.trim().length() > 140)
                         {
                             
                             Carteira cart2 = new Carteira();
                             cart2.setId(linhaTXT.substring(72,81).trim());
                             cart2.setDescricao(linhaTXT.substring(82,125));
    
                             aux1 = linhaTXT.substring(126,143);
                             aux1 = aux.replace(",",".");
                             aux1 = aux.trim();
    
                             t1 = new StringTokenizer(aux1);
                             aux1 = new String();
    
                             while(t1.hasMoreTokens())
                               aux1 += t1.nextToken(".");                    
    
                             cart2.setValor(Double.parseDouble(aux1));
                             cart2.setQuantidadeDeClientes(Integer.parseInt(linhaTXT.substring(143,(linhaTXT.length())).trim()));
                             carteiras.addCarteira(cart2);
                         }
                        
                         linhaTXT = input.nextLine();
                     }
     }
         }
         catch(NoSuchElementException e)
         {
             System.err.println(e);
             input.close();
     System.exit(1);
         }
    

    }

     public void closeFile()
    

    {
    if( input != null)
    input.close();
    }

     public Iterator listaCarteiras()
     {
         Iterator iterator = carteiras.createIterator();
         
         /*while(iterator.hasNext())
         {
             Carteira cart = (Carteira) iterator.next();
             
             System.out.print(cart.getId() + "  ");
             System.out.print(cart.getDescricao() + "  " );
             System.out.print(cart.getValor() + "  ");
             System.out.print(cart.getQuantidadeDeClientes() + "\n\n");
         }*/
         
         return iterator;
     }
     
     public ColecaoDeCarteiras getColecao()
     {
         return carteiras;
     }
    

}

Aqui eu pego as informações do TXT e faço uma coleção dos objetos q eu resgatei.

Testando.java: aqui eu faço um modelo da JTable e a JTable:

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.*;

/**

  • TableDemo is just like SimpleTableDemo, except that it

  • uses a custom TableModel.
    */
    public class Testando extends JPanel {
    private boolean DEBUG = true;

    public Testando() {
    super(new GridLayout(1,0));

     JTable table = new JTable(new MyTableModel());
     table.setPreferredScrollableViewportSize(new Dimension(500, 70));
     table.setFillsViewportHeight(true);
    
     //Create the scroll pane and add the table to it.
     JScrollPane scrollPane = new JScrollPane(table);
    
     //Add the scroll pane to this panel.
     add(scrollPane);
    

    }

    class MyTableModel extends AbstractTableModel {

     private String [] nomes = {"Código",
                                     "Descrição",
                                     "Valor",
                                     "Quantidade de Clientes","Adicionar ao Relatorio"}; 
                                     
    Vector<String> columnNames = new Vector<String>(Arrays.asList(nomes));
     
     /*                              
     private Object[][] data = {{"Mary", "Campione",
          "Snowboarding", new Boolean(false)},
         {"Alison", "Huml",
          "Rowing", new Boolean(true)},
         {"Kathy", "Walrath",
          "Knitting", new Boolean(false)},
         {"Sharon", "Zakhour",
          "Speed reading", new Boolean(true)},
         {"Philip", "Milne",
          "Pool", new Boolean(false)},
         {"Isaac", "Rabinovitch", 
             "Nitpicking", new Boolean(false)}};
     */
     
     private Vector<Object> data = pegaDados();
     
    
     
     public Vector<Object> pegaDados()
     {
     
     	Vector <Object> dataAux = new Vector();
     	
     	ManipulaTXT m = new ManipulaTXT();
     	ColecaoDeCarteiras c = m.getColecao();
     	Iterator iterator = c.createIterator();
     
         while(iterator.hasNext())
         {
             Carteira cart = (Carteira) iterator.next();
             Vector <Object> data1 = new Vector();
             
             data1.addElement((String) cart.getId());
             data1.addElement((String)cart.getDescricao());
             data1.addElement(new Double(cart.getValor()));
             data1.addElement(new Integer(cart.getQuantidadeDeClientes()));
             data1.addElement(new Boolean(false));
             
             dataAux.add(data1);
             
         }
         
         return dataAux;
         
     }
     
     
    
     public int getColumnCount() {
         return columnNames.size();
     }
    
     public int getRowCount() {
         return data.size();
     }
    
     public String getColumnName(int col) {
         return columnNames.elementAt(col);
     }
    
     public Object getValueAt(int row, int col) {
         return ((Vector)data.elementAt(row)).elementAt(col);
     }
     
    
     /*
      * JTable uses this method to determine the default renderer/
      * editor for each cell.  If we didn't implement this method,
      * then the last column would contain text ("true"/"false"),
      * rather than a check box.
      */
     public Class getColumnClass(int c) {
         return getValueAt(0, c).getClass();
     }
    
     /*
      * Don't need to implement this method unless your table's
      * editable.
      * Define apartir de qual coluna o usuário pode editar
      */
     public boolean isCellEditable(int row, int col) {
         //Note that the data/cell address is constant,
         //no matter where the cell appears onscreen.
         if (col < 3) {
             return false;
         } else {
             return true;
         }
     }
    
     /*
      * Don't need to implement this method unless your table's
      * data can change.
      */
     
     public void setValueAt(Object value, int row, int col) {
         if (DEBUG) {
             System.out.println("Setting value at " + row + "," + col
                                + " to " + value
                                + " (an instance of "
                                + value.getClass() + ")");
         }
    
     	((Vector)data.elementAt(row)).setElementAt(value, col);
         fireTableCellUpdated(row, col);
    
         if (DEBUG) {
             System.out.println("New value of data:");
             
         }
     }
    
     private void printDebugData() {
         int numRows = getRowCount();
         int numCols = getColumnCount();
    
         for (int i=0; i < numRows; i++) {
             System.out.print("    row " + i + ":");
             for (int j=0; j < numCols; j++) {
                 System.out.print("  " + ((Vector)data.elementAt(numRows)).elementAt(numCols));
             }
             System.out.println();
         }
         System.out.println("--------------------------");
     }
    
     public Vector<Object> getData() {
         return data;
     }
    

    }

    /**

    • Create the GUI and show it. For thread safety,

    • this method should be invoked from the

    • event-dispatching thread.
      */
      private static void createAndShowGUI() {
      //Create and set up the window.
      JFrame frame = new JFrame(“Manipulando Relatórios”);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      //Create and set up the content pane.
      Testando newContentPane = new Testando();
      newContentPane.setOpaque(true); //content panes must be opaque
      frame.setContentPane(newContentPane);

      //Display the window.
      frame.pack();
      frame.setVisible(true);

    }

    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application’s GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();

         }
     });
    

    }
    }

Quando eu vou rodar o programa dah o seguinte erro:

Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException
at com.projetos.banco.ManipulaTXT.pegaDadosTXT(ManipulaTXT.java:58)
at com.projetos.banco.ManipulaTXT.(ManipulaTXT.java:37)
at com.projetos.banco.Testando$MyTableModel.pegaDados(Testando.java:77)
at com.projetos.banco.Testando$MyTableModel.(Testando.java:68)
at com.projetos.banco.Testando.(Testando.java:31)
at com.projetos.banco.Testando.createAndShowGUI(Testando.java:196)
at com.projetos.banco.Testando.access$100(Testando.java:25)
at com.projetos.banco.Testando$1.run(Testando.java:211)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

Se alguém poder ajudar dah um help…aew…tow me batendo tem um tempinho já…
Desde já obrigado…

dica coloca sempre os seus códigos na tag ( code) mas vamos ao seu problema:

exceção disparada :

causa :

aonde ?

at com.projetos.banco.ManipulaTXT.pegaDadosTXT(ManipulaTXT.java)

opá achamos o lugar:

mas porque está disparando a exceção ?

Vlws aew…
Eu debuguei mais uma vez o código e vih q eskeci de colocar
openFile() dentro do método pegaDadosTXT…

Obrigado!!!
Vlws!!!