Adding JcheckBox in JTable

Hi there,
I have a JcheckBox in a JTable. Whenever I click the Checkbox , on that particular cell it display true , when Clicked and false when I click again. Is there any way that I could disable that ?, I also wanted to center the Jcheckbox ?
Thanks

Similar way I'm using in other class & it is working.But a JTable is not the same as other components, which is why you should be using Boolean values.
You responded to my post 12 minutes after I posted my reply. That did not give you enough time to read the tutorial and understand how to use a JTable correctly!!!

Similar Messages

  • Adding JCheckBox into JTable

    Hi all,
    I added a JCheckBox into a JTable, while clicking the check box the selection will not replicate into the JTable. Please help me to resolve this issue.
    * TableDemo.java
    * Created on September 5, 2006, 11:49 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package simPackage;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ButtonGroup;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.*;
    * @author aathirai
    public class TableDemo extends JPanel{
       // public JRadioButton[] dataButton;
        /** Creates a new instance of TableDemo */
        public TableDemo() {
            JCheckBox firstCheck = new JCheckBox("");
            Object[][] data={{firstCheck,"2","4","5","2"}};
                    String[] columnNames={"qr No","supplier kt code","part no","start date","end date"};
                    JTable searchResultTable = new JTable(data,columnNames);
                    searchResultTable.getColumn("qr No").setCellRenderer(new RadioButtonRenderer());
                    searchResultTable.getColumn("qr No").setCellEditor(new RadioButtonEditor(firstCheck));
            JScrollPane scrollPane = new JScrollPane(searchResultTable);
            //Add the scroll pane to this panel.
            add(scrollPane);
    public static void main(String args[])   {
         JFrame jFrame  = new JFrame("testing");
         jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TableDemo newContentPane = new TableDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            jFrame.setContentPane(newContentPane);
            //Display the window.
            jFrame.pack();
            jFrame.setVisible(true);
    class RadioButtonRenderer implements TableCellRenderer {
        public JCheckBox check1 = new JCheckBox("");
      public Component getTableCellRendererComponent(JTable table, Object value,
       boolean isSelected, boolean hasFocus, int row, int column) {
          check1.setBackground(Color.WHITE);
         return check1;
    class RadioButtonEditor extends DefaultCellEditor{
        public JCheckBox check1 = new JCheckBox("");
      boolean state;
      int r, c;
      JTable t;
      class RbListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
          if (e.getSource() == check1){
            state = true;
          else{
            state = false;
          RadioButtonEditor.this.fireEditingStopped();
      public RadioButtonEditor(JCheckBox checkBox) {
        super(checkBox);
      public Component getTableCellEditorComponent(JTable table, Object value,
       boolean isSelected, int row, int column) {
        RbListener rb = new RbListener();
        t = table;
        r = row;
        c = column;
        if (value == null){
          return null;
        check1.addActionListener(rb);
         //check1.setSelected(((Boolean)value).booleanValue());
        /*if (((Boolean)value).booleanValue() == true){
          check1.setSelected(true);
        return check1;
      public Object getCellEditorValue() {
        if (check1.isSelected() == true){
          return Boolean.valueOf(true);
        else{
          return Boolean.valueOf(false);
    }Thanks in advance.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    class TableDemo extends JPanel
      public TableDemo()
        //JCheckBox firstCheck = new JCheckBox("");
        //Object[][] data={{firstCheck,"2","4","5","2"}};
        Object[][] data={{new Boolean(false),"2","4","5","2"}};
        String[] columnNames={"qr No","supplier kt code","part no","start date","end date"};
        JTable searchResultTable = new JTable(data,columnNames);
        //searchResultTable.getColumn("qr No").setCellRenderer(new RadioButtonRenderer());
        //searchResultTable.getColumn("qr No").setCellEditor(new RadioButtonEditor(firstCheck));
        TableColumn tc = searchResultTable.getColumnModel().getColumn(0);
        tc.setCellEditor(searchResultTable.getDefaultEditor(Boolean.class));
        tc.setCellRenderer(searchResultTable.getDefaultRenderer(Boolean.class));
        JScrollPane scrollPane = new JScrollPane(searchResultTable);
        add(scrollPane);
      public static void main(String args[])
        JFrame jFrame  = new JFrame("testing");
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        TableDemo newContentPane = new TableDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        jFrame.setContentPane(newContentPane);
        jFrame.pack();
        jFrame.setVisible(true);
    }

  • Problem in Adding JCheckBox Object to JTable

    I want to add a JCheckBox Object to A JTbale Coloumn but it shows the following message in JTable Coloumn-
    javax.swing.JCheckBox[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@f9f9d8,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=2,bottom=2,right=2],paintBorder=false,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=].
    Help Me in solving this problem

    Hi,
    All the thing you have to do is to return a boolean for the column. JTable will use a checkbox (as default) to show boolean values.

  • Booleans not rendering as JCheckBoxes in JTable

    I've read several posts on trying to get JCheckBoxes to render in a JTable, and I've looked at the Tables tutorial, but I still can't figure out why my JTable isn't rendering Booleans as check-boxes. :-(
    I thought rendering check-boxes was the the default behavior for cells with Boolean values. This doesn't seem to be the case. I can add a cell editor of type JCheckBox by simply instantiating a new DefaultCellEditor, but adding a cell renderer doesn't look so easy (I believe I have to create my own implementation class). I was trying to avoid that, because a) I'm working in Servoy (which means I'm working in a Rhino editor and need to access my own custom classes as plugins or beans), and b) my Java skills are weak.
    So can anybody see anything about my code that is obviously wrong? Or do I have to roll up my sleeves and write my own DefaultTableCellRenderer bean/plugin?
    Here's my code (remember - it's javascript instances of java objects). (Note: I'm not sure exactly what kinds of objects JSDataSet.getAsTableModel() returns to the JTable model, but creating my own JTable with a vector of vectors of Boolean objects, or setting a Boolean in the cell after the fact doesn't work either.)
    Any tips would be greatly appreciated.
    // convert dataset into JTable
    var table = elements.monitoring;
    table.model = treatments.getAsTableModel();
    // modify column headers
    var columns = table.columnModel;
    columns.getColumn(0).setHeaderValue('Quantity');
    columns.getColumn(0).setPreferredWidth(60);
    columns.getColumn(1).setHeaderValue('Repeats/hr.');
    columns.getColumn(1).setPreferredWidth(75);
    columns.getColumn(2).setHeaderValue('TREATMENT');
    columns.getColumn(2).setPreferredWidth(225);
    // start treatment times at 8am
    var j=8;
    for (i=3;i<44;++i) {
         var j_int = Packages.java.lang.Integer(j);
         columns.getColumn(i).setHeaderValue(j_int);
         columns.getColumn(i).setPreferredWidth(10);
         if (j == 12) {
              j=0;
         ++j;
    // center cell data
    var cell_class = Packages.java.lang.String;
    var table_renderer = table.getDefaultRenderer(cell_class);
    table_renderer.setHorizontalAlignment(0);
    // add JTable to JScrollPane viewport (necessary to display headers)
    var viewport = elements.monitoring_pane.viewport;
    viewport.add(table);

    Ok, another problem -
    I wound up throwing out the Rhino constructor method and implementing my own JTable class and importing it into the Rhino scope. I had to do that because I needed columns to render different types of objects - basically, the table cells should appear blank until they are selected and data is added to them, at which point they should be Boolean and render check-boxes - I got that to work by overriding the getCellRenderer method.
    The problem is, I need to add some logic to the 'onClick' event for the table cell, so that I can add a blank check box, add a checked check box, or remove a check box. I looked at the Table tutorial and tried to do it by implementing the TableModelListener interface on my JTable and defining the tableChanged method. However, when I add the tableChanged method to my class, I get an ArrayIndexOutOfBoundsException.
    Any tips would be greatly appreciated.
    I instantiate the class in Rhino and add the TableModelListener like so:
    var table = new Packages.my_classes.MyJTable();
    table.model = model; // a working model defined elsewhere
    table.getModel().addTableModelListener(table);Here's my class:
    package my_classes;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class MyJTable extends JTable implements TableModelListener {
         public TableCellRenderer getCellRenderer(int row, int column) {
              Object value = getValueAt(row,column);
                if (value == null) {
                     return getDefaultRenderer(JCheckBox.class);
                return super.getCellRenderer(row,column);
         public Class getColumnClass(int column) {
              if (column > 2) {
                   return Boolean.class;
              } else {
                   return Object.class;
         public void tableChanged(TableModelEvent e) {
              int row = e.getFirstRow();
              int column = e.getColumn();
              TableModel model = (TableModel) e.getSource();
              String columnName = model.getColumnName(column);
              Object data = model.getValueAt(row, column);
    }

  • Can not show the JCheckBox in JTable cell

    I want to place a JCheckBox in one JTable cell, i do as below:
    i want the column "d" be a check box which indicates "true" or "false".
    String[] columnNames = {"a","b","c","d"};
    Object[][] rowData = {{"", "", "", Boolean.FALSE}};
    tableModel = new DefaultTableModel(rowData, columnNames);
    dataTable = new JTable(tableModel);
    dataTable.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(new JCheckBox()));
    But when i run it, the "d" column show the string "false" or "true", not the check box i wanted.
    I do not understand it, can you help me?
    Thank you very much!
    coral9527

    Do not use DefaultTableModel, create your own table model and you should implement the method
    getColumnClass to display the boolean as checkbox ...
    I hope the following colde snippet helps you :
    class MyModel extends AbstractTableModel {
              private String[] columnNames = {"c1",
    "c2"};
    public Object[][] data ={{Boolean.valueOf(true),"c1d1"}};
         public int getColumnCount() {
         //System.out.println("Calling getColumnCount");
         return columnNames.length;
    public int getRowCount() {
    //System.out.println("Calling row count");
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    data[row][col] = value;
    fireTableCellUpdated(row, col);

  • Problem adding JTextFeild on JTable

    Hi,
    I have a JTable and I added then added a JTextFeild to a particular column.For that i used the following code.
    public class PackageCellEditor extends DefaultCellEditor {
         public PackageCellEditor(JTextField jTextFeild) {
              super(jTextFeild);          
         public Component getTableCellEditorComponent(JTable table, Object value,
                   boolean isSelected, int row, int column) {
         if (value==null) return null;
    //     ((JTextField)getComponent()).setPreferredSize(new Dimension(2,2));
    //     ((JTextField)getComponent()).setMaximumSize(new Dimension(3,3));
    //     ((JTextField)getComponent()).setMinimumSize(new Dimension(2,2));
    //     ((JTextField)getComponent()).setOpaque(true);
    //     ((JTextField)getComponent()).set
         return (JTextField)getComponent();
    //     public Object getCellEditorValue(){
    }problem is while editing the text that i am typing is not visible completely since the size of the JTextFeild is more than the cell.Once the editing is complete the typed data is shown properly inside the cell.
    How to adjust the size of the JTextFeild inside the cell to fit it to the size of the cell itself.???
    Thnx
    Neel

    Try using getTableCellEditorComponent() instead of getComponent().

  • Double clicking for editing JCheckBox in JTable under java 1.6?

    Hi all,
    I have a JTable with JCheckboxes in a column (and associated renderer and editor). All worked good with/until java 1.5.
    Now with java 1.6 I have to click two times on the checkbox in order to change the selection...
    Anyone has experimented a similar problem??

    I have spent some hours over this strange problem finding no way to solve it and no workaround.
    Could this be a bug introduced with java 1.6?
    Note that the behaviour is more strange as what I hade described in my last post:
    - mouse click on a cell with a checkbox: checkbox CHANGE state
    - mouse click on other celll with checkbox: NO EFFECT
    - click on other celll: checkbox CHANGE state
    - click on other celll: NO EFFECT
    - click on other celll: checkbox CHANGE state
    - click on other celll: NO EFFECT
    - click on other celll: checkbox CHANGE state
    - click on other celll: NO EFFECT
    - ... and so on
    Really strange, at least for me...

  • Problem in adding JComboBox in JTable

    Hi,
    I was trying to put some comboxes in a jtable. The problem is I am not able to add combo boxes in the 1st and 2nd column. But its adding from the 3rd column. What can be wrong in the following code?
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import javax.swing.*;
    * TableRenderDemo is just like TableDemo, except that it
    * explicitly initializes column sizes and it uses a combo box
    * as an editor for the Sport column.
    public class TableRenderDemo1 extends JPanel {
        private boolean DEBUG = true;
            DefaultTableCellRenderer renderer =  new DefaultTableCellRenderer();
        public TableRenderDemo1() {
            //super(new GridLayout(1,0));
            JTable table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(500, 250));
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Set up column sizes.
            initColumnSizes(table);
            //Fiddle with the Sport column's cell editors/renderers.
            setUpNameColumn(table, table.getColumnModel().getColumn(3));
            //Fiddle with the Sport column's cell editors/renderers.
            setUpSportColumn(table, table.getColumnModel().getColumn(4));
            //Add the scroll pane to this panel.
            add(scrollPane);
            String strPlaf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
            try {
                    UIManager.setLookAndFeel(strPlaf);
                    SwingUtilities.updateComponentTreeUI(scrollPane);
            } catch(Exception e) {
                    e.printStackTrace();
         * This method picks good column sizes.
         * If all column heads are wider than the column's cells'
         * contents, then you can just use column.sizeWidthToFit().
        private void initColumnSizes(JTable table) {
            MyTableModel model = (MyTableModel)table.getModel();
            TableColumn column = null;
            Component comp = null;
            int headerWidth = 0;
            int cellWidth = 0;
            Object[] longValues = model.longValues;
            TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
            for (int i = 0; i < 5; i++) {
                column = table.getColumnModel().getColumn(i);
                comp = headerRenderer.getTableCellRendererComponent(
                                     null, column.getHeaderValue(),
                                     false, false, 0, 0);
                headerWidth = comp.getPreferredSize().width;
                comp = table.getDefaultRenderer(model.getColumnClass(i)).
                                 getTableCellRendererComponent(
                                     table, longValues,
    false, false, 0, i);
    cellWidth = comp.getPreferredSize().width;
    if (DEBUG) {
    System.out.println("Initializing width of column "
    + i + ". "
    + "headerWidth = " + headerWidth
    + "; cellWidth = " + cellWidth);
    //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
    column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    public void setUpSportColumn(JTable table, TableColumn sportColumn) {
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Snowboarding");
    comboBox.addItem("Rowing");
    comboBox.addItem("Knitting");
    comboBox.addItem("Speed reading");
    comboBox.addItem("Pool");
    comboBox.addItem("None of the above");
    comboBox.setVisible(true);
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    renderer.setToolTipText("Click for combo box");
    sportColumn.setCellRenderer(renderer);
    public void setUpNameColumn(JTable table, TableColumn nameColumn) {
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("One");
    comboBox.addItem("Two");
    comboBox.addItem("Three");
    comboBox.addItem("Four");
    comboBox.addItem("Five");
    comboBox.setVisible(true);
    nameColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    renderer.setToolTipText("Click for combo box");
    nameColumn.setCellRenderer(renderer);
    class MyTableModel extends AbstractTableModel {
    private String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    private Object[][] data = {
    {"Mary", "Saikat", "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Srinath", "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Sheela", "Knitting", new Integer(2), new Boolean(false)},
    {"John", "Yashwant", "Something", new Integer(5), new Boolean(true)},
    {"Harry", "Jay", "Playing", new Integer(1), new Boolean(true)},
    public final Object[] longValues = {"Sharon", "Campione",
    "None of the above",
    new Integer(20), Boolean.TRUE};
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col < 2) {
    return false;
    } else {
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[i][j]);
    System.out.println();
    System.out.println("--------------------------");
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("TableRenderDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    TableRenderDemo1 newContentPane = new TableRenderDemo1();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    Thanks in advance.

    First, I don't see where you are tying to set the combo box on the first two columns. I only see it for the 3 and 4.
    Also why are you putting combo boxes in columns that are not editable:
            public boolean isCellEditable(int row, int col) {
                //Note that the data/cell address is constant,
                //no matter where the cell appears onscreen.
                if (col < 2) {
                    return false;
                } else {
                    return true;
            }

  • How to insert jcheckbox in jtable

    hello
    i am user of oracle9i jdeveloper using jclient/swing .
    question:
    how to insert jcheckbox at a particular cell in jtable.
    please reply to me if anyone amongst you know the solution.
    thank you

    Please continue the discussion here: how to insert checkbox at a particular  cell  in jtable
    Correct me if this is not about the same subject.

  • Adding JButtons to JTable

    Hello all,
    How can I add JButtons to a JTable?
    I found an article that is supposed to show you how to do just that:
    http://www.devx.com/getHelpOn/10MinuteSolution/20425
    I downloaded the code in the article and it works to an extent - I can see the buttons in the table but the buttons seem as if they are disabled :( Since I used this code in my application, I get the same behavior too.
    Is there a bug in the code? Is there a simpler solution? What am I missing?
    Raj

    Thanks. That makes the button clickable. But now the button changes back to it's old value when you click on another cell. I suppose that's because we have 2 buttons, one for rendering and one for editing. So I added a setValueAt(Object value, int row, int column) to MyModel. This works throws class cast exception.
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class ButtonInTable extends JFrame {
        JTable t=new JTable(new MyModel());
        public ButtonInTable() {
            this.getContentPane().add(new JScrollPane(t));
            this.setBounds(50,50,300,200);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            t.setDefaultEditor(Object.class,new ButtonEditor());
            t.setDefaultRenderer(Object.class,new ButtonRenderer());      
        public static void main(String[] args) {
            ButtonInTable buttonInTable1 = new ButtonInTable();
            buttonInTable1.show();
        class ButtonEditor extends JButton implements TableCellEditor {
            Object currentValue;
            Vector listeners=new Vector();
            public ButtonEditor() {
                            this.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    currentValue=JOptionPane.showInputDialog("Input new value!");
                                    if (currentValue!=null) {
                                        setText(currentValue.toString());
            public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
                currentValue=value;
    //            this.setText(value.toString());
                this.setText( ((JButton)value).getText() );
                return this;
            public Object getCellEditorValue() {
                return currentValue;
            public boolean isCellEditable(EventObject anEvent) {
                return true;
            public boolean shouldSelectCell(EventObject anEvent) {
                return true;
            public boolean stopCellEditing() {
                ChangeEvent ce=new ChangeEvent(this);
                for (int i=0; i<listeners.size(); i++) {
                    ((CellEditorListener)listeners.get(i)).editingStopped(ce);
                return true;
            public void cancelCellEditing() {
                ChangeEvent ce=new ChangeEvent(this);
                for (int i=0; i<listeners.size(); i++) {
                    ((CellEditorListener)listeners.get(i)).editingCanceled(ce);
            public void addCellEditorListener(CellEditorListener l) {
                listeners.add(l);
            public void removeCellEditorListener(CellEditorListener l) {
                listeners.remove(l);
        class ButtonRenderer extends DefaultTableCellRenderer {
            public Component getTableCellRendererComponent
                    (JTable table, Object button, boolean isSelected, boolean hasFocus, int row, int column) {
                return (JButton)button;
        class OldModel extends DefaultTableModel {
            public OldModel() {
                super(new String[][]{{"1","2"},{"3","4"}},new String[] {"1","2"});
        class MyModel extends AbstractTableModel {
            private String[] titles = { "A", "B" };
            private Object[][] summaryTable =
                    { new JButton("11"), new JButton("12") },
                    { new JButton("21"), new JButton("22") }
            public MyModel(){
                super();
            public int getColumnCount() {
                return titles.length;
            public String getColumnName(int col) {
                return titles[col];
            public int getRowCount() {
                return summaryTable.length;
            public Object getValueAt(int row, int col) {
                return summaryTable[row][col];
            public void setValueAt(Object value, int row, int column) {
                summaryTable[row][column] = value;
                fireTableCellUpdated(row, column);
            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();
            public boolean isCellEditable(int row, int col) {
                return true;
    }

  • Adding checkbox to JTable cell

    Hi, I am tryin to add a checkbox to JTabel cell.
    But somehow i am ending up getting 'false' in the cell instead of checkbox.
    Can anyone please help me.
    here is my getColumnClass and getValuAt
    public Class getColumnClass(int column)
    { if(column==0) return Boolean.class;
         else return Object.class;
    public Object getValueAt(int nRow, int nCol) {
         if(nCol==0)
              return new Boolean(ch.isSelected());
    }

    You can use a cell rederer that will give you more flexibility .
    Add the renderer to a specific column and that will do the job.
    Here is the example:
    public class CheckBoxRenderer extends JCheckBox implements  TableCellRenderer {
        public CheckBoxRenderer() {
            super();
        public Component getTableCellRendererComponent(JTable table, java.lang.Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {
            Color c = table.getBackground();
            this.setBackground(c);
            setSelected(value != null && ((Boolean) value).booleanValue());
            return this;
    }In order to edit the value in a check box you will need to write a cell editor which
    is going to be easy.

  • Help with adding rows to JTable

    Could any body help me with the following problem:
    I have created form where I use JTable.Initially I should show 5 rows in JTable. User can enter data into the cells.And commit I should store the data in database.
    My problem is how to dynamically add rows to JTable as user is entering the data. And how to retain the data in the cells when it is entered.
    Right now when user edits a cell and tabs to next one the data in previous cell disappears.
    Its Urgent can anybody help me
    Thanks in advance
    Babu

    The number of rows, number of columns, etc, are all determined by the TableModel used in the JTable.
    What is the easiest solution is to subclass AbstractTableModel adding methods to support your dynamic row adding/deleting/etc that you need. If you go to the javadoc for JTable, there's a link to a tutorial which contains most of what you need to know.
    - David

  • (URGENT) jCheckBox in jTable

    I have a jTable inwhich I would like to have a column of jCheckBox.
    I can I do that ???

    class MyTableModel extends AbstractTableModel
       //These are the object Types of the columns represented by this TableModel
        static final Class[] COLUMN_TYPES = new Class[]{
            String.class, Boolean.class, Integer.class, etc...};
        //without getColumnClass() only Strings are displayed
        //this method is what displays the Boolean class as a checkBox etc.
        public Class getColumnClass(int column)
            return COLUMN_TYPES[column];
    }

  • JCheckBox in JTable..urgent!!!

    hello all, can you please help me on how to add JCheckBox on each row of JTable?..the value of JCheckBox is not true or false..i just use it for user options.. please help!!

    Are you trying to create a checkbox in each row or just a few? Let me know.
    Yinka...

  • Problem in adding image in jtable cells

    hi all.
    im creating a swing application using netbeans 6.0.
    i want to display image in cells of one column.
    for that i set an "image icon" directly to that cell in the "default table model", in that case it is displaying the path of that image in that cell!
    then i created a new label, and set the image as icon of that label. added that label in that cell. in this case it is printing label.tostring() to that cell!!
    please help.
    thanks in advance.

    You need to override getColumnClass to return Icon.class for the column containing the icon. A code snippet that demonstrates how you might do this:      table = new JTable (new DefaultTableModel (data, colNames) {
             public Class getColumnClass (int columnIndex) {
                switch (columnIndex) {
                   case 0: return Calendar.class;
                   case 1: return String.class;
                   case 2: return Icon.class;
                   //case 2: return Boolean.class;
                return null;
          });luck, db

Maybe you are looking for

  • TF20015: The field 'Assigned To' contains the value 'xyz' that is not in the list of supported values.

    When creating a new work item, a list of valid users is populated in the 'assigned to' drop down list. When I select one of the listed domain user values, the drop down color changes to yellow and the error 'TF20015...' is shown. When selecting the u

  • Pdf drag and drop directly to device?

    I used to be able to do this with my Ipod Touch 4G but now i seem to be forced to add to the books library on itunes and afterwards press sync, at the least id like not to be forced to press sync =/ but i remember that i used to be able to just find

  • Macbook Pro 10.6 will not boot

    Last night I had a kernel panic. When the system tried restarting it stuck on the grey/blue screen with the Apple logo and spinning wheel. I have tried booting in safe mode: same screen. I have booted with my OSX install disk and run a disk repair, w

  • Cannot start dbca

    After getting problems with the DBCA when enabling it to run immediately after install I tried reinstalling 11g without configuring a db after install and everything went fine, but when I start dbca from a terminal I get the same crash: [oracle@local

  • Extension Builder 1.0.1 Posted

    Hi all, We've just released a new build of ExtensionBuilder, 1.0.1, to the Eclipse update site at http://cssdk.host.adobe.com/cssdk/update/ If you've already installed Extension Builder, you can get this by selecting Help > Check for Updates and foll