Re: JCheckBox in JTable cell




":-o" <fcrutch@xxxxxxxxxxxx> wrote in message
news:455be$4363e023$d8080ef2$25911@xxxxxxxxxxxxxxxx
> Thanks in advance,
>
> I'm trying to put a JCheckBox (and will add listener to it) into a JTable
> cell.
>
> Can someone take a look at this and tell me where I'm going wrong?
>
> import java.awt.*;
> import java.awt.event.*;
> import javax.swing.*;
> import javax.swing.table.*;
> import javax.swing.event.*;
> public class Test extends JFrame
> { Container cp = getContentPane();
> JTable table = null;
> Object columnNames[] = {"Col1", "Col2", "Col3", "Col4"};
> Object cell[][] = null;
> Test()
> {
> table = new JTable();
> cell = new CheckboxRenderer[1][4];
> for (int row=0; row < 1; ++row)
> {
> for (int col=0; col < 4; ++col)
> {
> cell[row][col] = new CheckboxRenderer(table, row, col);
> table.setDefaultRenderer(
> ((JCheckBox)cell[row][col].getCheckbox()).getClass(),cell[row][col]);
> }
> }
> cp.setLayout(new BorderLayout());
> cp.add( table = new JTable(cell, columnNames), BorderLayout.CENTER);
> pack();
> setVisible(true);
> }
>
> public static void main(String args[]) { new Test(); }
> }
>
> class CheckboxRenderer extends JPanel implements TableCellRenderer
> {
> public JCheckBox cb = new JCheckBox("",false);
> protected JTable table = null;
> protected int row = 0;
> protected int col = 0;
> public JCheckBox getCheckbox() { return cb; }
> CheckboxRenderer(JTable table, int row, int col)
> {
> this.table = table;
> this.row = row;
> this.col = col;
> setLayout(new FlowLayout());
> add(cb);
> }
> public Component getTableCellRendererComponent(JTable table,
> Object value, boolean isSelected, boolean hasFocus,
> int row, int column)
> {
> return this;
> }
>
> }
>

is this what you're trying to do?

import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;

class Testing extends JFrame
{
String colNames[] = {"Col1", "Col2", "Col3", "Col4"};
Object[][] data = null;
DefaultTableModel dtm;
public Testing()
{
setLocation(400,100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
dtm = new DefaultTableModel(data,colNames);
JTable table = new JTable(dtm);
JScrollPane sp = new JScrollPane(table);
TableColumn tc = table.getColumnModel().getColumn(0);
tc.setCellEditor(table.getDefaultEditor(Boolean.class));
tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
getContentPane().add(sp);
for(int x = 0; x < 5; x++)
{
dtm.addRow(new Object[]{new Boolean(false),"Row "+(x+1)+" Col 2",
"Row "+(x+1)+" Col 3","Row "+(x+1)+" Col 4"});
}
pack();
}
public static void main (String[] args){new Testing().setVisible(true);}
}


.