Duvida cellrender e celleditor

5 respostas
M

ola pessoal …

criei 2 classes para formatar os campos de uma tabela (pra valores monetarios) usando celleditor e cellrenderer …

ai vai minha tabela :

modelo = new DefaultTableModel( dado , colu );   
	    jTable1 = new JTable( modelo );  // linha e coluna
  	    jTable1.setVisible(true);
	    jTable1.getTableHeader().setReorderingAllowed(false);
	    jTable1.getTableHeader().setResizingAllowed(false);
	    jTable1.getTableHeader().setBackground( Color.lightGray ) ;
	    jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	    jTable1.setGridColor( Color.black );
	    jTable1.setShowHorizontalLines(true) ;
	    jTable1.setShowVerticalLines(true) ;
	    jTable1.setEnabled(true);
	    jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
	    jTable1.getColumnModel().getColumn(0).setPreferredWidth( 100 );
	    jTable1.getColumnModel().getColumn(1).setCellEditor(new MoedaCellEditor());
	    jTable1.getColumnModel().getColumn(1).setCellRenderer(new MoedaCellRender());
	    modelo.setRowCount(10);
public class MoedaCellRender extends JLabel implements TableCellRenderer {

	/**
	 * classe para mostrar a celula com formato de moeda
	 */
	private static final long serialVersionUID = 1L;
	private JLabel cell = null;
	private NumberFormat formatter = NumberFormat.getCurrencyInstance( new Locale("pt","BR") ); // Locale.getDefault()
	
	private JLabel getCell() {
		if (cell == null)
			cell = new JLabel();
		return cell;
	}

	public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
		if (value != null) {
			getCell().setText( formatter.format(value) );
			getCell().setHorizontalAlignment(SwingConstants.RIGHT);
		} else getCell().setText("");
		return getCell();
	}
}
public class MoedaCellEditor extends AbstractCellEditor implements TableCellEditor {
	
	/**
	 * classe para editar a celula com formato de moeda
	 */
	private static final long serialVersionUID = 1L;
	private JFormattedTextField moeda = null;
	private NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("pt","BR"));
	
	private JFormattedTextField getCell() {
		if (moeda == null)
			moeda = new JFormattedTextField(formatter);
		return moeda;
	}

	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
		getCell().setValue(value);
		return getCell();
	}

	public Object getCellEditorValue() {
		return getCell().getValue();
	}

}

quando executo o programa, ele aparece normalmente com a formatacao, mas quando digito alguma coisa no campo, um valor qualquer, na saida do focus ele fica em branco, como se eu nao tivesse digitado nada, o que pode se …
a tabela ta com o comando pra ser editavel

5 Respostas

M

ola so pessoal …
criei essa daqui para datas e funciona, consigo mudar as datas …

public class DateCellRender extends JLabel implements TableCellRenderer {

	/**
	 * classe para mostrar a celula com formato de data
	 */
	private static final long serialVersionUID = 1L;
	private JLabel cell = null;
	
	private JLabel getCell() {
		if (cell == null)
			cell = new JLabel("");
		return cell;
	}

	public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
		if (value != null) {
			getCell().setText(new SimpleDateFormat("dd/MM/yyyy").format((Date)value)) ;
			getCell().setHorizontalAlignment(SwingConstants.CENTER);
		} else getCell().setText("");
		return getCell();
	}

}
public class DateCellEditor extends AbstractCellEditor implements TableCellEditor {
	
	/**
	 * classe para editar a celula com formato de data
	 */
	private static final long serialVersionUID = 1L;
	private DateField cell = null;
	
	private DateField getCell() {
		if (cell == null)
			cell = new DateField();
		return cell;
	}

	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
		getCell().setValue(value);
		return getCell();
	}

	public Object getCellEditorValue() {
		return getCell().getValue();
	}

}

a diferenca eh que no primeiro eu usava jformatedtextfield, agora to usando datefield da classe "net.sf.nachocalendar.components.DateField"
pode ser isso ?? porque ?? como fazer isso pra jformatedtextfield ??
e no retorno eu usei : getCell().setText(new SimpleDateFormat(“dd/MM/yyyy”).format((Date)value)) ; ao inves de : getCell().setText( formatter.format(value) );

o que pode ser ??

obrigado

eltonk

Certficação?! :roll:

T

Vou mudar este post para “Interface Gráfica” - Swing não cai na prova de SCJP, e na prova de SCJD você não precisa obrigatoriamente fazer as coisas com isto.

M

alguém ??
estou precisando muito disso …

M

para eu pegar o valor de uma determinada celula selecionada numa jtable, sem usar celleditor e sem cellrender, estou usando e está dando certo …

Object obj = jTable1.getValueAt( jTable1.getSelectedRow(), jTable1.getSelectedColumn() );

mas quando eu coloco um jformattedtextfield numa celula, por exemplo, esse objeto me retorna null, mesmo que eu digito qualquer coisa na celula, o que eu digito “some” quando vou para outra celula
o que pode ser isso, como pegar o valor que foi digitado, e como deixar o valor, nao fazer “sumir” ???

obrigado

Criado 10 de maio de 2007
Ultima resposta 4 de nov. de 2008
Respostas 5
Participantes 3