Problemas em Modelo de Jtable ao editar

3 respostas
Alchemist

Opa blz ai pessoal ?

Eu tenho uma table que não tem cabeçalho, a primeira coluna dela é como se fosse o cabeçado dela, o resto das celulas terão que aceitar double, eu gostaria que a tabela fica-se em branco no começo, então eu seto o Objeto de dados como null:

Object[][] teste = {  
			        {new Double(2), new Double(2),new Double(2),new Double(2),
			         new Double(2), new Double(2),new Double(2),new Double(2),
			         new Double(2), new Double(2),new Double(2),new Double(2)},
			        {new Double(2), new Double(2),new Double(2),new Double(2),
				     new Double(2), new Double(2),new Double(2),new Double(2),
				     new Double(2), new Double(2),new Double(2),new Double(2)},
			 }; 
		 
		 
		 String colunasNome[] = {"Dados", "Double"};
		 
		 Modelo modelo = new Modelo(colunasNome,teste);
		
		 JTable table =  new JTable(modelo);

blz ele cria a tabela certinha e tal, olha o meu modelo:

//2

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;

public class Modelo extends AbstractTableModel{
    
	   private NumberFormat format;
	   private String[] nomeColuna;
	   
	   private Object[][] dados;  
	   
	   public Modelo(String[] nomeColuna, Object[][] dados){
		   this.dados = dados;
		   this.nomeColuna   = nomeColuna;
		   
		   format = DecimalFormat.getCurrencyInstance(new Locale("pt","BR"));  
		   format.setMinimumFractionDigits(2);
	    }  
	   
	   public int getColumnCount() {
		   return 13;
	   }   

	   public int getRowCount() {
		   return nomeColuna.length;  
	   }

 
	   public Object getValueAt(int rowIndex, int columnIndex) {
			
		   if(columnIndex == 0){
				return  nomeColuna[rowIndex];
			}else{
				return dados[rowIndex][columnIndex-1];
			}
	   } 
	   
	   
	    public boolean isCellEditable(int rowIndex, int columnIndex) {  
	    	return columnIndex != 0; 
		}
	   
	
	   public Class getColumnClass(int columnIndex) {
           
		   Object o = getValueAt(0, columnIndex);
			if(columnIndex!=0){     
				if (o == null) {
					return Object.class;
				} else {
					return o.getClass();
				}
			}else{
				System.out.println("Classe String");
				return String.class;
			}
	   	}

	   public void setValueAt(Object value, int rowIndex, int columnIndex) {  
		   //NumberFormat numeroFormatado = NumberFormat.getCurrencyInstance();
		   System.out.println(value);
		   dados[rowIndex][columnIndex-1] = format.format(value);;
		   fireTableCellUpdated(rowIndex, columnIndex);  
	   }




	
	


}

Então o meu problema é que quando eu passo nomeu objeto como null, e depois tendo colocar um valor ele da este erro

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Cannot format given Object as a Number
	at java.text.DecimalFormat.format(Unknown Source)
	at java.text.Format.format(Unknown Source)
	at javax.swing.JTable$DoubleRenderer.setValue(Unknown Source)
	at javax.swing.table.DefaultTableCellRenderer.getTableCellRendererComponent(Unknown Source)
	at javax.swing.JTable.prepareRenderer(Unknown Source)
	at javax.swing.plaf.basic.BasicTableUI.paintCell(Unknown Source)
	at javax.swing.plaf.basic.BasicTableUI.paintCells(Unknown Source)
	at javax.swing.plaf.basic.BasicTableUI.paint(Unknown Source)
	at javax.swing.plaf.ComponentUI.update(Unknown Source)
	at javax.swing.JComponent.paintComponent(Unknown Source)
	at javax.swing.JComponent.paint(Unknown Source)
	at javax.swing.JComponent.paintWithOffscreenBuffer(Unknown Source)
	at javax.swing.JComponent.paintDoubleBuffered(Unknown Source)
	at javax.swing.JComponent._paintImmediately(Unknown Source)
	at javax.swing.JComponent.paintImmediately(Unknown Source)
	at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
	at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
	at java.awt.event.InvocationEvent.dispatch(Unknown Source)
	at java.awt.EventQueue.dispatchEvent(Unknown Source)
	at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.run(Unknown Source)

o metodo que da problema é este

public Class getColumnClass(int columnIndex) {
           
		   Object o = getValueAt(0, columnIndex);
			if(columnIndex!=0){     
				if (o == null) {
					return Object.class;
				} else {
					return o.getClass();
				}
			}else{
				System.out.println("Classe String");
				return String.class;
			}
	   	}

Como eu posso arrumar isto? eu sei que ele n pode converter pq eu setei como Object.class o campo, o que eu poderia colocar no lugar ?

3 Respostas

Marky.Vasconcelos

Pela StackTrace parece que o erro está no setValueAt. Veja o que voce esta passando como argumento.

Eder_Peixoto

Number.class?

O método getColumnClass deve retornar a classe que a coluna suporta.

Eder_Peixoto

Observação: a classe JTable utiliza na camada model a classe DefaultTableModel. Por que você está extendendo a AbstractTableModel, pois aquela já possui toda a implementação necessária?

Caso o objetivo seja modificar o modo como os valores são apresentados, altere o renderizador da célula (método setCellRenderer).

Se necessitar alterar o modo como os dados são editados nas células, modifique o editor (método setCellEditor).

Criado 7 de julho de 2009
Ultima resposta 7 de jul. de 2009
Respostas 3
Participantes 3