Como definir um renderer em uma JTable?!?

1 resposta
K

Salve galera....

estou desenvolvendo um projetinho em java e preciso criar uma tabela... está tabela contém apenas duas colunas: a primeira na verdade serve apenas como indice das células (1...N). Já a segunda coluna é onde o usuário fornecerá os valores com os quais irei trabalhar.

Porém sou iniciante em java e estou apanhando pra entender como funciona uma tabela... com base no tutorial do Bruno Rios aqui do GUJ já implementei alguma idéia mas estou com problema para definir o renderer... ao rodar acusou erro na hora de invocar o método setCellRenderer... outro erro ocorre quando vou adicionar e remover uma linha da tabela...

se alguém puder ajudar agradeço!!

abraço moçada!

public class tabela extends JFrame implements ActionListener{

	private static final long serialVersionUID = 1L;

	JPanel painel;

	JTable jtable;

	JButton add;

	JButton rem;
 
	TableModel tab;
	
	DecimalFormat formatter = new DecimalFormat("0.00");
	
	public tabela() {

		getContentPane().setLayout(null);
		setBounds(100, 100, 600, 600);
		setTitle("TABELA");

		add = new JButton("Adiciona linha");
		add.setBounds(100, 500, 130, 25);
		add.addActionListener(this);

		rem = new JButton("Remove linha");
		rem.setBounds(350, 500, 130, 25);
		rem.addActionListener(this);

		painel = new JPanel();
		painel.setBounds(0, 0, 600, 400);

		jtable = new JTable();
		jtable = createJTable();
        
		JScrollPane scrollPane = new JScrollPane(jtable);

		painel.add(scrollPane);
		getContentPane().add(painel);
		getContentPane().add(add);
		getContentPane().add(rem);
	}

	public static void main(String arg[]) {
		JFrame tab = new tabela();
		tab.setVisible(true);
	}

	
	public void actionPerformed(ActionEvent Evento) {
		Object ObjetoRecebeuEvento;
		ObjetoRecebeuEvento = Evento.getSource();

		if (ObjetoRecebeuEvento == add) {
           int linha = jtable.getRowCount()+1;
           tab.addRow(new String[] {Integer.toString(linha), "" });
		}

		if (ObjetoRecebeuEvento == rem) {
           int linha = jtable.getSelectedRow();
           tab.removeRow(linha);
		}
	}
	
	public JTable createJTable() {

		ArrayList dados = new ArrayList();
		String[] colunas = new String[] { "", "X" };

		// Alimenta as linhas de dados
		dados.add(new String[] { "1", "" });
		dados.add(new String[] { "2", "" });
		dados.add(new String[] { "3", "" });
		dados.add(new String[] { "4", "" });
		dados.add(new String[] { "5", "" });
		dados.add(new String[] { "6", "" });
		dados.add(new String[] { "7", "" });
		dados.add(new String[] { "8", "" });
		dados.add(new String[] { "9", "" });
		dados.add(new String[] { "10", "" });

		TableModel modelo = new TableModel(dados, colunas);
		JTable jtable = new JTable(modelo);
		jtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		jtable.getColumn("X").setCellRenderer(new DecimalRenderer(formatter)); //acusou erro nesta parte

		return jtable;

	}

	class DecimalRenderer extends DefaultTableCellRenderer {

		private static final long serialVersionUID = 1L;
		DecimalFormat  formatter;
		  
		  DecimalRenderer(String pattern) {
		    this(new DecimalFormat(pattern));
		  }
		  
		  DecimalRenderer(DecimalFormat formatter) {
		    this.formatter = formatter;
		    setHorizontalAlignment(JLabel.RIGHT);
		  }
		  
		  public void setValue(Object value) { 
		    setText((value == null) ? ""
		      : formatter.format(((Double)value).doubleValue())); 
		  }
		}
}

modelo da tabela

import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.table.AbstractTableModel;

public class TableModel extends AbstractTableModel {

	private static final long serialVersionUID = 1L;

	private ArrayList linhas = null;

	private String[] colunas = null;
	
	public String[] getColunas() {
		return colunas;
	}

	public ArrayList getLinhas() {
		return linhas;
	}

	public void setColunas(String[] strings) {
		colunas = strings;
	}

	public void setLinhas(ArrayList list) {
		linhas = list;
	}

	public int getColumnCount() {
		return getColunas().length;
	}

	public int getRowCount() {
		return getLinhas().size();
	}

	public Object getValueAt(int rowIndex, int columnIndex) {
		// Obtem a linha, que é uma String []
		String[] linha = (String[]) getLinhas().get(rowIndex);
		// Retorna o objeto que esta na coluna
		return linha[columnIndex];
	}

	public TableModel(ArrayList dados, String[] colunas){
		setLinhas(dados);
		setColunas(colunas);
	}

	
	public boolean isCellEditable(int row, int col) {
		if(col == 1)
			return true;
		return false;
	}

	public void setValueAt(Object value, int row, int col) {
		// Obtem a linha, que é uma String []
		String[] linha = (String[]) getLinhas().get(row);
		// Altera o conteudo no indice da coluna passado
		linha[col] = (String) value;
		// dispara o evento de celula alterada
		fireTableCellUpdated(row, col);
	}
	
	public void addRow( String [] dadosLinha){
	     getLinhas().add(dadosLinha);
	     // Informa a jtable de que houve linhas incluidas no modelo
	     // COmo adicionamos no final, pegamos o tamanho total do modelo
	    // menos 1 para obter a linha incluida.
	     int linha = getLinhas().size()-1;
	     fireTableRowsInserted(linha,linha);
	     return;
	}
	
	 public void removeRow(int row){
		     getLinhas().remove(0);
		     // informa a jtable que houve dados deletados passando a 
		     // linha removida
		     fireTableRowsDeleted(row,row);
		 }
		 
		 
		 /**
		  * Remove a linha pelo valor da coluna informada
		  * @param val
		  * @param col
		  * @return
		  */
		 public boolean removeRow(String val, int col){
		     // obtem o iterator
		     Iterator i = getLinhas().iterator();
		     int linha = 0;
		     // Faz um looping em cima das linhas
		     while(i.hasNext()){
		         // Obtem as colunas da linha atual
		         String[] linhaCorrente = (String[])i.next();
		         linha++;
		         // compara o conteudo String da linha atual na coluna desejada
		         // com o valor informado
		         if( linhaCorrente[col].equals(val) ){
		             getLinhas().remove(linha);
		             // informa a jtable que houve dados deletados passando a 
		             // linha removida
		             fireTableRowsDeleted(linha,linha);
		             return true;                
		         }
		     }
		     // Nao encontrou nada
		     return false;
		 }
}

1 Resposta

K

ninguém :?: :?: :?:

Criado 13 de fevereiro de 2008
Ultima resposta 15 de fev. de 2008
Respostas 1
Participantes 1