Por que não consigo colocar checkBox no meu TableModel?

Olá,

Já tentei de tudo para colocar um checkBox na primeira coluna da minha tabela. Aparecem true ou false. Quando clico sobre a coluna, o checkbox aparece mas, ao soltar o mouse, volta a aparecer true ou false. Alguém pode me ajudar ?

[code]/*

  • Created on 06/02/2006

*/
package telaRelatorioPorExecutante;

import java.util.List;
import java.util.Vector;

import javax.swing.table.AbstractTableModel;

import negocioRelatorioPorExecutante.BeanLote;
import br.com.dixamico.negocio.Lote;

public class ModeloLote extends AbstractTableModel {

private static final long serialVersionUID = 1L;
public final int SELECIONADO = 0;
public final int LOTE = 1;
public final int EXTRATO = 2;
public static final int ENTREGA = 3;
public final int VENCIMENTO = 4;


final String[] columnNames = {"",
		  "Nº do Lote",
   		  "Extrato pgto",
		  "Data entrega",
		  "Data vencimento"
		  };

// public List rows = new LinkedList();
public Vector<Object> rows = new Vector<Object>();

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

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

public Object getValueAt(int rowIndex, int columnIndex) {
	Vector linha = (Vector) rows.elementAt(rowIndex);
	switch (columnIndex){
	case SELECIONADO : 
		return (Boolean)linha.get(columnIndex);
	case LOTE:
		return new Lote(String.valueOf(linha.get(columnIndex))).loteFormatado();
	default :
		return linha.get(columnIndex);
	}
	
}

public void setValueAt(Object o, int rowIndex, int columnIndex){
	Vector linha = (Vector) rows.get(rowIndex);
	linha.setElementAt(o,columnIndex);
}

public Class&lt;?&gt; getColumnClass(int aColumn) { 
	return getValueAt(0, aColumn).getClass();
}

public String getColumnName(int aColumn) {
	return columnNames[aColumn];
}

public boolean isCellEditable(int aRow, int aColumn){
	return (aColumn==SELECIONADO?true:false);
}

public void colocaDados(List&lt;BeanLote&gt; listaDeLotes) {
	rows.clear();
	for (BeanLote umBean:listaDeLotes){
		Vector&lt;Object&gt; linha = new Vector&lt;Object&gt;();
		linha.add(new Boolean(true));
		linha.add(umBean.getLote());
		linha.add(umBean.formadaData(umBean.getExtratoPagamento()));
		linha.add(umBean.formadaData(umBean.getDataEntrega()));
		linha.add(umBean.formadaData(umBean.getDataVencimento()));
		rows.add(linha);
	}
	this.fireTableDataChanged();
}

}
[/code]

Obrigado,
Márcio

Você tem que substituir alguns métodos do JTable para conseguir fazer isso… dá uma olhada no link abaixo que ele explica tudo

http://java.sun.com/docs/books/tutorial/uiswing/components/table.html

Cara não entendi a parte do getValueAt seu:

 	public Object getValueAt(int rowIndex, int columnIndex) {
 		Vector linha = (Vector) rows.elementAt(rowIndex);
 		switch (columnIndex){
 		case SELECIONADO : 
 			return (Boolean)linha.get(columnIndex);
 		case LOTE:
 			return new Lote(String.valueOf(linha.get(columnIndex))).loteFormatado();
 		default :
 			return linha.get(columnIndex);
 		}
 		
 	}

Não seria assim o certo ?

	public Object getValueAt(int row, int column) {
		Item item = (Item) dataVector.get(row);
		switch (column) {
		case SELECIONADO:
			Boolean b = new Boolean(item.isSelecionado());
			return b;
 		case LOTE:
 			return new Lote(String.valueOf(linha.get(columnIndex))).loteFormatado();
		default:
			return new Object();
		}
	}

Ao invéz de colocá-los em um vector, eu coloco no objeto, no caso um item.

ateub,

No tutorial da Sun o método getColumnClass seria o responsável por traduzir um Boolean por um checkbox, o que não está ocorrendo. Ja fiz outras tabelas com checkboexs, mas esta não está saidno, e eu não sei porque?

Márcio

Roda este exemplo aqui e veja se pode te ajudar… :idea:

import java.awt.Component;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.EventObject;

import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.event.CellEditorListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;

/**
 * @version 1.0 11/09/98
 */

class ComboString {
  String str;

  ComboString(String str) {
    this.str = str;
  }

  public String toString() {
    return str;
  }
}

class MultiRenderer extends DefaultTableCellRenderer {
  JCheckBox checkBox = new JCheckBox();

  public Component getTableCellRendererComponent(JTable table, Object value,
      boolean isSelected, boolean hasFocus, int row, int column) {
    if (value instanceof Boolean) { // Boolean
      checkBox.setSelected(((Boolean) value).booleanValue());
      checkBox.setHorizontalAlignment(JLabel.CENTER);
      return checkBox;
    }
    String str = (value == null) ? "" : value.toString();
    return super.getTableCellRendererComponent(table, str, isSelected,
        hasFocus, row, column);
  }
}

class MultiEditor implements TableCellEditor {
  private final static int COMBO = 0;

  private final static int BOOLEAN = 1;

  private final static int STRING = 2;

  private final static int NUM_EDITOR = 3;

  DefaultCellEditor[] cellEditors;

  JComboBox comboBox;

  int flg;

  public MultiEditor() {
    cellEditors = new DefaultCellEditor[NUM_EDITOR];
    comboBox = new JComboBox();
    comboBox.addItem("true");
    comboBox.addItem("false");
    cellEditors[COMBO] = new DefaultCellEditor(comboBox);
    JCheckBox checkBox = new JCheckBox();
    //checkBox.setOpaque( true );
    checkBox.setHorizontalAlignment(JLabel.CENTER);
    cellEditors[BOOLEAN] = new DefaultCellEditor(checkBox);
    JTextField textField = new JTextField();
    cellEditors[STRING] = new DefaultCellEditor(textField);
    flg = NUM_EDITOR; // nobody
  }

  public Component getTableCellEditorComponent(JTable table, Object value,
      boolean isSelected, int row, int column) {
    if (value instanceof ComboString) { // ComboString
      flg = COMBO;
      String str = (value == null) ? "" : value.toString();
      return cellEditors[COMBO].getTableCellEditorComponent(table, str,
          isSelected, row, column);
    } else if (value instanceof Boolean) { // Boolean
      flg = BOOLEAN;
      return cellEditors[BOOLEAN].getTableCellEditorComponent(table,
          value, isSelected, row, column);
    } else if (value instanceof String) { // String
      flg = STRING;
      return cellEditors[STRING].getTableCellEditorComponent(table,
          value, isSelected, row, column);
    }
    return null;
  }

  public Object getCellEditorValue() {
    switch (flg) {
    case COMBO:
      String str = (String) comboBox.getSelectedItem();
      return new ComboString(str);
    case BOOLEAN:
    case STRING:
      return cellEditors[flg].getCellEditorValue();
    default:
      return null;
    }
  }

  public Component getComponent() {
    return cellEditors[flg].getComponent();
  }

  public boolean stopCellEditing() {
    return cellEditors[flg].stopCellEditing();
  }

  public void cancelCellEditing() {
    cellEditors[flg].cancelCellEditing();
  }

  public boolean isCellEditable(EventObject anEvent) {
    return cellEditors[flg].isCellEditable(anEvent);
  }

  public boolean shouldSelectCell(EventObject anEvent) {
    return cellEditors[flg].shouldSelectCell(anEvent);
  }

  public void addCellEditorListener(CellEditorListener l) {
    cellEditors[flg].addCellEditorListener(l);
  }

  public void removeCellEditorListener(CellEditorListener l) {
    cellEditors[flg].removeCellEditorListener(l);
  }

  public void setClickCountToStart(int n) {
    cellEditors[flg].setClickCountToStart(n);
  }

  public int getClickCountToStart() {
    return cellEditors[flg].getClickCountToStart();
  }
}

public class MultiComponentTable extends JFrame {

  public MultiComponentTable() {
    super("MultiComponent Table");

    DefaultTableModel dm = new DefaultTableModel() {
      public boolean isCellEditable(int row, int column) {
        if (column == 0) {
          return true;
        }
        return false;
      }
    };
    dm.setDataVector(
        new Object[][] {
            { new ComboString("true"), "ComboString", "JLabel",
                "JComboBox" },
            { new ComboString("false"), "ComboString", "JLabel",
                "JComboBox" },
            { new Boolean(true), "Boolean", "JCheckBox",
                "JCheckBox" },
            { new Boolean(false), "Boolean", "JCheckBox",
                "JCheckBox" },
            { "true", "String", "JLabel", "JTextField" },
            { "false", "String", "JLabel", "JTextField" } },
        new Object[] { "Component", "Data", "Renderer", "Editor" });

    JTable table = new JTable(dm);
    table.getColumn("Component").setCellRenderer(new MultiRenderer());
    table.getColumn("Component").setCellEditor(new MultiEditor());

    JScrollPane scroll = new JScrollPane(table);
    getContentPane().add(scroll);
    setSize(400, 160);
    setVisible(true);
  }

  public static void main(String[] args) {
    MultiComponentTable frame = new MultiComponentTable();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
  }
} 

Um abraço.

RESOLVI !

Eu havia criado um método que definia os renderes da table e havia a seguinte linha, modeloDaColuna.getColumn(0).setCellRenderer(rendererCentro);

Bastou comentar a linha que funcionou.

Obrigado a todos,

Márcio

Boa tarde,

Tenho um jtable onde a primeira coluna é checkbox. Gostaria que dependendo do caso, o check ficasse (in)visível.

Alguém já teve de implementar isso? Criei um renderer para a coluna, e trato cada célula, mas o setVisible parece não surtir efeito. Mas se eu mudar a cor de fundo da célula tudo ocorre bem.

Segue o código do Renderer.

class CheckRenderer extends JCheckBox implements TableCellRenderer{
public CheckRendererInvisible (){
super ();
setHorizontalAlignment(SwingConstants.CENTER);
}

// Note that the value, row and column are all parameters to this method.
public Component getTableCellRendererComponent (final JTable table, Object value, boolean isSelected,
                                                boolean hasFocus, final int row, final int column){
	    	
	TableSorter sorter = (TableSorter)table.getModel();
    Table tb = (Table)sorter.getTableModel();
	Boolean canCheck = tb.isRegistroAtualizavel(row);    	
    
	setSelected( Boolean.valueOf( value.toString() ).booleanValue() );
	
    updateSelectionColors(table, isSelected, canCheck);
    updateFocusBorder(hasFocus);

    return this;
}    

private void updateSelectionColors(JTable table, boolean isSelected, boolean canCheck) {
	if (isSelected) {            
		this.setBackground(table.getSelectionBackground());
	} else {            
		this.setBackground(table.getBackground());
	}
	if (!canCheck) {
		setBackground(Color.LIGHT_GRAY);
		setVisible(false);

// setEnabled(false);
// setFocusable(false);
}
}

private void updateFocusBorder (boolean hasFocus) {
    if (hasFocus) {
        this.setBorder (UIManager.getBorder ("Table.focusCellHighlightBorder"));
    } else {
        this.setBorder (new EmptyBorder(1, 1, 1, 1));
    }
}

}

Alguém tem alguma sugestão?

Att