tags:

views:

104

answers:

2

Hello, I cannot put jChceckBox to jTable cell. More likely I can put checkBox to table, but when I run module with that table, the cell where should be checkBox shows text "true" or "false". The behaviors of that cell are the same like checkbox, but it shows text value instead of checkbox.

Here is the code.

DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(new Object[][]{{"dd", "Edit", "Delete"},
                                {"dd","Edit", "Delete"}},
                 new Object[]{"Include","Component", "Ekvi"});
jTable1 = new javax.swing.JTable();

jTable1.setModel(dm);


JCheckBox chBox=new JCheckBox();
jTable1.getColumn("Include").setCellEditor(new DefaultCellEditor(chBox));
jScrollPane1.setViewportView(jTable1);
A: 

The cell editor defines how the data inside your table behave according to editing its value, what you need is the right TableCellRenderer to properly display the checkbox inside the cell:

final JCheckBox checkBox = new JCheckBox();
jTable1.getColumn("Include").setCellRenderer(new DefaultTableCellRenderer() {
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
      check.setSelected(((Boolean)value).booleanValue()) ;
      return check;
    }
});
Jack
-1, there is no need to create a custom renderer. JTable already provides a default renderer and editor for Boolean values.
camickr
Yes, but in this way you understand how it works. In the other way you just solve this specific problem without getting further knowledge.
Jack
@Jack: Your point has merit, and your example matches the questioner's usage; but the tutorial mentioned by @camickr offers a more versatile approach. You might add a reference to your answer. http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editrender
trashgod
@camickr But this is not working with another component that I need to use too - jCombobox. So this explanation has bigger value for me although camickr's answer is closer to my question and offers more simple solution.
joseph
you mean mine or the one suggested by camickr?
Jack
I mean camickr's solution does not work with JComboboxes.
joseph
@joseph: the tutorial, cited several places, addresses both issues. In particular, http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#renderer
trashgod
+4  A: 

Read the JTable API and follow the link to the Swing tutorial on "How to Use Table" for a working example.

Basically you store Boolean values in the TableModel, then you override the getColumnClass() method to return the class of each colulmn and the table will choose the appriate renderer and editor.

camickr