Checkboxes in JTable

Hi,
i need to create a table with 8 columns.
7th column will be a checkbox.
i created a table with the help of a class that extends cellrenderer class.
but i cldnt check or uncheck the checkbox.
IS there any other way to create a column with checkboxes?
Please help me.

This site has plenty of examples for you to choose from. Choose one of the simple ones and then take a look at the code.
http://crionics.com/products/opensource/faq/swing_ex/JTableExamples2.html

Similar Messages

  • How to use checkboxes in jtable ?

    I am trying to use checkboxes in
    JTable,I set the property in the jtable column to boolean.The proplem is that i do no know how to use this property in java program.My intension is that,I will have a java form and a java button on it,by clicking the button, i will have to write a code,for example a code that fetches records from a table and displays them on the jtable(on the user interface),when I select the check box corresponding to any row,It should let me either delete or edit that row and this modification has to be reflected to the table in the database. At this time,i can fetch and display but i can not delete or modify any row because I do no know how to use the check box inside the jtable.
    Thank you for your help!

    Multi-post: http://forum.java.sun.com/thread.jspa?threadID=5273661&tstart=0

  • Problem with checkbox in JTable when using MyTableModel

    Hi all,
    I have been trawling these message boards for days looking for the answer to my question but have not had any success.
    I am extending AbstractTabel model to create MyTableModel which returns a vector containing the results of a MySql query. One column in this query returns a "0" or "1" which I then store as the boolean value into the vector so that it is rendered as a checkbox on the screen.
    I have also overridden the setValueAt method. THe problem is that when I attempt to check the box in the table, the checkbox isn't actually checking.
    Do I need to implement some sort of listener which picks up the user clicking the box and refresh the model?
    Here is my model code:
    public class MyTableModel extends AbstractTableModel {
        private Vector v = null;
        int listId;
        MyTableModel(int listId){
            this.listId = listId;
            v = new ListItemManagement().getFullList(listId);
       public Class getColumnClass(int c) {
            switch(c) {
                case 6:
                    return Boolean.class;
                default:
                    return Object.class;
        public String getColumnName(int colIndex){
            return ((String[])v.get(0))[colIndex];
        public int getColumnCount() {
            return ((String[])v.get(0)).length;
        public int getRowCount() {
            return (v.size() - 1);
        public Object getValueAt(int rowIndex, int colIndex) {
            return ((Object[])v.get(rowIndex + 1))[colIndex];
        public void setValueAt(Object aValue, int rowIndex, int colIndex) {
            System.out.println("Value: " + String.valueOf(aValue));
            Object row[] = (Object[]) v.elementAt(rowIndex);
            if(colIndex<6){
                row[colIndex] = (String)aValue;
            else{
                row[colIndex] = (Boolean)aValue;
            v.setElementAt(row, rowIndex);
            fireTableCellUpdated(rowIndex, colIndex);
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            return ! (col < 6);
        }Here is the getFullList function which returns the vector:
                rs = stmt.executeQuery();
                ResultSetMetaData colData = rs.getMetaData();
                int columnCount = colData.getColumnCount();
                String[] columnNames = new String[columnCount];
                for (int i = 0; i < columnCount; i++){
                    columnNames[i] = colData.getColumnName(i + 1);
                Vector v = new Vector();
                v.add(columnNames);
                while (rs.next()){
                    Object[] values = new Object[columnCount];
                    for (int i = 0; i < (columnCount-1); i++){
                        values[i] = rs.getString(i + 1);
                    int sel = rs.getInt("selected");
                    System.out.println(sel);;
                    if(sel==0){
                        values[columnCount-1]=new Boolean(false);
                    else if (sel==1)
                        values[columnCount-1]=new Boolean(true);
                    v.add(values);
                rs.close();
                stmt.close();
                return v;

    Thanks for the replies, much appreciated.
    I've looked at the Swing jtable tutorial and added a TableModelListener and have managed to achieve the desired results but for one thing.
    When I attempt to check the box on the first row of the jTable I get a runtime error:
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayStoreException: java.lang.Boolean
    at project.MyTableModel.setValueAt(MyTableModel.java:65)
    I have been playing around with the setValueAt method and it is in my original post. Here is how it currently looks:
        public void setValueAt(Object aValue, int rowIndex, int colIndex) {
            System.out.println("Value: " + String.valueOf(aValue));
            Object row[] = (Object[]) v.elementAt(rowIndex);
            if(colIndex<6){
                row[colIndex] = (String)aValue;
            else{
                    if(getValueAt(rowIndex,colIndex).toString()=="true"){
                    row[6] = new Boolean(false);
                else{
                    row[6] = new Boolean(true);
            v.setElementAt(row, rowIndex);
            fireTableCellUpdated(rowIndex, colIndex);
        }

  • Problem with Checkbox in JTable

    This table here displays data from my MS Access database. It has 3 columns. Also I added the 4th column where this column contains checkboxes where I can select any row from the table. The checkboxes won't show except this "javax.swing.JCheckBox[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@1571886,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=]". I have no problem displaying the table. Here's my coding.
    public Contact() {
    super(new GridLayout(1,0));
    Vector heading = new Vector();
              heading.addElement("Name");
              heading.addElement("Contact number");
              heading.addElement("Detail");
              heading.addElement(new JCheckBox(););
              Vector data = new Vector();
    try
    // Load the Database Driver Class
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("Driver loaded successfully.");
    // Establish a connection with parameter values for
    // database connection URL, username, password
    Connection con =
    DriverManager.getConnection("jdbc:odbc:db1","","");
    System.out.println("Connection established successfully.");
    try
    // Create a statement
    Statement stmt = con.createStatement();
    System.out.println("Statement created successfully.");
    String sql = "SELECT * FROM Contact";
    String[] columnNames = {"Name", "Contact Number", "Detail"};
    ResultSet rs = stmt.executeQuery(sql);
    System.out.println("SQL Query executed successfully.");
    System.out.println("Output the data from the result set");
    while (rs.next())
    Vector row = new Vector();
    row.addElement(rs.getString("Name"));
    row.addElement(rs.getString("Contact number"));
    row.addElement(rs.getString("Detail"));
    row.addElement(new JCheckBox());
    data.addElement(row);
    System.out.println("Output Completed.");
              rs.close();
    stmt.close();
    finally
    con.close();
    catch (Exception e)
    e.printStackTrace();
    final JTable table = new JTable(data, heading);
    table.setPreferredScrollableViewportSize(new Dimension(500, 500));
    table.setFillsViewportHeight(true);
    JScrollPane scrollPane = new JScrollPane(table);
    add(scrollPane);
    Where have I gone wrong? Please help.

    First of all:
    a) Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
    http://forum.java.sun.com/help.jspa?sec=formatting
    b) In the future, Swing related questions should be posted in the Swing forum.
    Now for the answer to your question, read the JTable API. You will find a link to the Swing tutorial on "How to Use Tables" which shows you the proper way to display Boolean data with a JCheckBox renderer.

  • Urgent help needed in Checkbox in JTable

    I am trying to put a checkbox in the JTable. The value from the database is a string . The column name is checked. I want if hte value in the database is "yes" the column should be checked and if it is "no" it should not be checked or vice versa( if i check it, in database it should update the value as yes).
    I have the following code, it does not work. I try to click and it does not get clicked, Do you have anys suggestions P;ease help.
    if (checked == null)
    TableColumn column = table.getColumn("Checked");
    checked = new JCheckBox();
    // column.setCellRenderer(new CheckedBox());
    column.setCellEditor(new DefaultCellEditor(checked));
    checked.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent event)
    isChecked = checked.isSelected();
    class CheckedBox extends JCheckBox implements TableCellRenderer
    public CheckedBox()
    setHorizontalAlignment(JRadioButton.CENTER);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column)
    setEnabled(((Boolean)value).booleanValue());
    return this;

    You really need to study this tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    After you have read it, take a look at this example, and tweak it to suit your needs:
    import javax.swing.table.*;
    import javax.swing.*;
    public class Test {
      public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.getContentPane().add(new JScrollPane(new JTable(new MyTableModel())));
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    class MyTableModel extends AbstractTableModel {
      private String columnNames[] = new String[] {
          "Name", "Checked"
      private Class columnClasses[] = new Class[] {
          String.class, Boolean.class
      private Object data[][] = new Object[][] {
          { "One", Boolean.TRUE },
          { "Two", Boolean.FALSE },
          { "Three", Boolean.FALSE },
          { "Four", Boolean.TRUE },
      public int getColumnCount() {
        return columnNames.length;
      public int getRowCount() {
        return data.length;
      public Object getValueAt(int rowIndex, int columnIndex) {
        return data[rowIndex][columnIndex];
      public Class getColumnClass(int columnIndex) {
        return columnClasses[columnIndex];
      public String getColumnName(int columnIndex) {
        return columnNames[columnIndex];
      public boolean isCellEditable(int rowIndex, int columnIndex) {
        if (columnIndex == 1)
          return true;
        else
          return false;
      public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        data[rowIndex][columnIndex] = aValue;
    }

  • Listener for CheckBoxes in JTable

    Hi,
    I have a table that displays a checkbox in one of the fields. Which event handler/ listener should I use? Eg: Checkbox listener, List listener or otherwise?
    A change in the checkbox value (tick or untick) will trigger recalculation.
    Thanks.

    I can't really understand your problem.
    Here's a simple example that will print out the new check box state when you press the checkbox:
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableModel;
    public class TableCheckboxListenerExample {
        public static void main(String[] args) {
            try {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
                DefaultTableModel model = new DefaultTableModel(new Object[][] {{Boolean.FALSE, "Row 1"}, {Boolean.TRUE, "Row 2"}}, new String[] {"col1", "col2"}) {
                    public Class<?> getColumnClass(int columnIndex) {
                        if (getRowCount() > 0 && getValueAt(0, columnIndex) != null)
                            return getValueAt(0, columnIndex).getClass();
                        return super.getColumnClass(columnIndex);
                model.addTableModelListener(new TableModelListener() {
                    public void tableChanged(TableModelEvent e) {
                        int row = e.getFirstRow();
                        int column = e.getColumn();
                        TableModel model = (TableModel)e.getSource();
                        Object data = model.getValueAt(row, column);
                        if (data instanceof Boolean)
                            System.out.println("Value changed in Row: " + row + " Column: " + column + " New Value = " + data);
                JTable table = new JTable(model);
                frame.add(new JScrollPane(table));
                frame.pack();
                frame.setVisible(true);
            catch (Exception e) {e.printStackTrace();}       
    }

  • 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.

  • Add CheckBox to JTable

    How to add a checkBox in a column of my table?
    I would like to add a checkbox in column 3. Where should I add the Listener to?

    Here's a simple example using a JCheckBox as a renderer:
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.text.*;
    public class TableRenderer extends JFrame
        public TableRenderer()
            String[] columnNames = {"Date", "String", "Integer", "Decimal", "Boolean"};
            Object[][] data =
                {new Date(), "A", new Integer(1), new Double(5.1), new Boolean(true)},
                {new Date(), "B", new Integer(2), new Double(6.2), new Boolean(false)},
                {new Date(), "C", new Integer(3), new Double(7.3), new Boolean(true)},
                {new Date(), "D", new Integer(4), new Double(8.4), new Boolean(false)}
            DefaultTableModel model = new DefaultTableModel(data, columnNames);
            JTable table = new JTable( model )
                //  Returning the Class of each column will allow different
                //  renderers to be used based on Class
                public Class getColumnClass(int column)
                    return getValueAt(0, column).getClass();
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
            //  Create cell renderer
            TableCellRenderer centerRenderer = new CenterRenderer();
            //  Use renderer on a specific column
            TableColumn column = table.getColumnModel().getColumn(3);
            column.setCellRenderer( centerRenderer );
            //  Use renderer on a specific Class
            table.setDefaultRenderer(String.class, centerRenderer);
              scrollPane.getViewport().setBackground(Color.red);
        public static void main(String[] args)
            TableRenderer frame = new TableRenderer();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
        **  Center the text and highlight the focused cell
        class CenterRenderer extends DefaultTableCellRenderer
            public CenterRenderer()
                setHorizontalAlignment( CENTER );
            public Component getTableCellRendererComponent(
                JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
                super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                if (hasFocus)
                    setBackground( Color.cyan );
                else if (isSelected)
                    setBackground( table.getSelectionBackground() );
                else
                    setBackground( table.getBackground() );
                return this;
    }For more information on "Using Tables" see the Swing tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html

  • Multiple selection of checkbox  in  jtable

    hi
    I am using jtable in which first coloumn is using checbox.Ihave used celleditor and cell renderer for that.I want to check multiple checboxes
    at a time and on click of update button wanto send that information to database.But i m not able to check multiple checkboxes.As sson as i click on 2nd checkbox prwvious selection get cleared.Please help me as soon as possible.

    .Ihave used celleditor and cell renderer for that.I want to check multiple checboxesThere is no need to use custom renderers or editors, they are provided by the JTable.
    Read the JTable API and follow the link to the Swing tutorial on "How to Use Tables" for a working example.

  • Issue when clicking checkbox inside JTable

    The following exception in displayed when populating a table that is created extending the JTable, and clicking on the checkbox that is present in one of the cells. Any idea !!!!!!!!!!!!!
    java.lang.NullPointerException
    at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.setValueIsAdjusting(BasicTableUI.java:480)
    at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mouseReleased(BasicTableUI.java:534)
    at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:232)
    at java.awt.Component.processMouseEvent(Component.java:5100)

    Post a small demo code that is generally compilable, runnable and could reproduce your problem. See: http://homepage1.nifty.com/algafield/sscce.html and http://www.yoda.arachsys.com/java/newsgroups.html

  • Checkbox inside jtable

    I have the following sample code in which i wanted to include checkbox in the 3rd column. How to insert?
    import java.awt.Dimension;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class simpletable extends JPanel
         public simpletable()
              String[] columnNames={"FName","LName","Vegetarian"};
              Object[][] datas={ {"Harry","Potter",new Boolean(true)},{"William","Shakespeare",new Boolean(true)}};
              final JTable table=new JTable(datas, columnNames);
              table.setPreferredScrollableViewportSize(new Dimension(400, 50));
              JScrollPane scrollPane = new JScrollPane(table);
              add(scrollPane);
              int numRows = table.getRowCount();
              int numCols = table.getColumnCount();
              javax.swing.table.TableModel model = table.getModel();
              System.out.println("Value of data: ");
              for (int i = 0; i < numRows; i++)
              System.out.print(" row " + i + ":");
              for (int j = 0; j < numCols; j++)
              System.out.print(" " + model.getValueAt(i, j));
                   private static void createAndShowGUI()
                   JFrame.setDefaultLookAndFeelDecorated(true);
                   JFrame frame = new JFrame("SimpleTableDemo");
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   simpletable newContentPane = new simpletable();
                   newContentPane.setOpaque(true); // content panes must be opaque
                   frame.setContentPane(newContentPane);
                   frame.pack();
                   frame.setVisible(true);
              public static void main(String[] args)
              javax.swing.SwingUtilities.invokeLater(new Runnable()
                        public void run()
                             createAndShowGUI();
    }

    Hi,
    If u want to place a check box in a table u need to place the rederer and editor of the check box.
    pls find the editor and redorer for the check box.
    public class CheckBoxCellEditor extends JCheckBox implements TableCellEditor {
    protected ChangeEvent changeEvent = new ChangeEvent(this);
    protected EventListenerList listenerList = new EventListenerList();
    boolean selected = false;
    boolean cellEnabled = true;
    * Constructs a new <code>CheckBoxCellEditor</code> object.
    public CheckBoxCellEditor() {
    super();
    this.setSize(10, 10);
    addItemListener(new ItemListener() {
    * Invoked when item event occurs.
    * @param event <code> ItemEvent</code>
    public void itemStateChanged(ItemEvent event) {
    fireEditingStopped();
    * Registers the <code>CellEditorListener</code> to listeners list
    * @param l a <code>CellEditorListener</code>
    public void addCellEditorListener(CellEditorListener l) {
    listenerList.add(CellEditorListener.class, l);
    * To cancel the Cell Editing invoked all the actions with this cell will be cancelled
    public void cancelCellEditing() {
    fireEditingCanceled();
    * Returns the cell editor value as <code>Object</code> this will be called when stops the
    * cell editing
    * @return Object
    public Object getCellEditorValue() {
    return new Boolean(this.isSelected());
    * Returns the Editor Component to be painted on the table for the given row and column with
    * given value.
    * <p>
    * in the method we need to set the value and state of component then return component itself so
    * that it can be painted as it is on the table.
    * @param table <code>JTable</code> is the component where this editor need to be painted.
    * @param value <code>Object</code> is the value for the EditorComponent.
    * @param isSelected boolean
    * @param row int
    * @param column int
    * @return <code>Component</code> is the editor component to be painted on the table.
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
    int row, int column) {
    selected = isSelected;
    this.requestFocus();
    if (table.isCellEditable(row, column)) {
    this.setEnabled(true);
    else {
    this.setEnabled(false);
    if (value.equals(new Boolean(true))) {
    this.setSelected(true);
    else {
    this.setSelected(false);
    return this;
    * sets the state of the cell.
    * @param enabled boolean
    public void setCellEnabled(boolean enabled) {
    cellEnabled = enabled;
    * Determines whether this editor component is Editable or not if the return value is true then
    * it will behave as editable component other wise it can not allow to edit
    * @param anEvent <code>EventObject</code>
    * @return boolean
    public boolean isCellEditable(EventObject anEvent) {
    return cellEnabled;
    * Remove the <code>CellEditorListener</code> from the listeners list.
    * @param l <code>CellEditorListener</code>
    public void removeCellEditorListener(CellEditorListener l) {
    listenerList.remove(CellEditorListener.class, l);
    * Returns whether cell should be selectble or not when some event occurs.
    * @param anEvent <code>EventObject</code>
    * @return boolean
    public boolean shouldSelectCell(EventObject anEvent) {
    return true;
    * Stops the cell Editing invoked when the focus lost from this editorcomponent and puts the
    * values into model
    * @return boolean
    public boolean stopCellEditing() {
    fireEditingStopped();
    return true;
    * Invoked when stops the cell editing by removing thefocus from the editor component.
    public void fireEditingStopped() {
    CellEditorListener listener;
    Object[] listeners = listenerList.getListenerList();
    for (int i = 0; i < listeners.length; i++) {
    if (listeners[i] == CellEditorListener.class) {
    listener = (CellEditorListener) listeners[i + 1];
    listener.editingStopped(changeEvent);
    * Invoked when stops the cell editing when call cancell cell edit method on perticular cell it
    * will removes all editing values
    public void fireEditingCanceled() {
    CellEditorListener listener;
    Object[] listeners = listenerList.getListenerList();
    for (int i = 0; i < listeners.length; i++) {
    if (listeners[i] == CellEditorListener.class) {
    listener = (CellEditorListener) listeners[i + 1];
    listener.editingCanceled(changeEvent);
    and rederer is
    public class CheckBoxCellRendrer extends JCheckBox implements TableCellRenderer {
    public boolean cellEnabled = true;
    * Constructs a new <code>CheckBoxCellRendrer</code> object.
    public CheckBoxCellRendrer() {
    super();
    this.setEnabled(true);
    * Prepares and Returns the Button Renderer component for the table cell to be renderered this
    * will set the value and state of the component then paints on table cell
    * @param table <code>JTable</code> component where the renderer to be painted
    * @param value <code>Object</code> value for the renderer
    * @param isSelected boolean
    * @param hasFocus boolean
    * @param row int
    * @param column int
    * @return <code>Component</code>
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
    boolean hasFocus, int row, int column) {
    if (table.isCellEditable(row, column)) {
    this.setEnabled(true);
    else {
    this.setEnabled(false);
    if (value != null && value.equals(new Boolean(true))) {
    this.setSelected(true);
    else {
    this.setSelected(false);
    return this;
    * sets the state of the cell
    * @param enabled boolean
    public void setCellEnabled(boolean enabled) {
    cellEnabled = enabled;
    * determines whether this cell is editable or not
    * @param anEvent <code>EventObject</code>
    * @return boolean
    public boolean isCellEditable(EventObject anEvent) {
    return cellEnabled;
    * determines whether this cell is editable or not
    * @param anEvent <code>EventObject</code>
    * @return boolean
    public boolean isCellEnabled(EventObject anEvent) {
    return cellEnabled;
    u need to use the below code to place these in tabe
    TableColumn column1 = ((TableColumnModel) ttable.getColumnModel()).getColumn(1);
    column1.setPreferredWidth(25);
    CheckBoxCellEditor editor1 = new CheckBoxCellEditor();
    column1.setCellEditor(editor1);
    CheckBoxCellRendrer renderer1 = new CheckBoxCellRendrer();
    column1.setCellRenderer(renderer1);
    this may help u.
    regards
    jeevan

  • Checkbox in jtable

    hi, i am trying to make a table that one of her columns is a checkbox column, but i want it to be full checkbox like this : [checkbox] [label] this example should be on one cell.
    i know i have to implement some interfaces but i dont know which or how? can some one give me those two interfaces, but please give example how to implement them.
    Edited by: shuky19 on Jul 20, 2008 2:54 AM

    thank you for the help but i couldnt find what i a looking for in the link you gave me, can you please direct me to the chapter and the file which can help me?

  • JckechBox into JTable -- getselectedrow

    I have a problem with Checkbox into JTable
    My table has checkbox into first column. If I select checkbox, the program open a new JPanel. To do this I have associated an ActionListener to CheckBox that seems to work fine. This is the related code:
    public class AbstractAction implements ActionListener{            
         private static final long serialVersionUID = 1L;     
        public void actionPerformed(ActionEvent evt) {
            JCheckBox cb = (JCheckBox)evt.getSource();
            alarm_NOack_table.getSelectedRow()
            boolean isSel = cb.isSelected();
            if (isSel) {
        } else {
       };As you can see, in the listener I need to know the row number in which there is the selected checkbox, but alarm_NOack_table.getSelectedRow() return always '-1'.
    How can I do?
    Thanks in advance
    Palmis

    hey!!!
    you will have to use TableModelListener
    if you have a look at API
    getSelectedRow()
    Returns the index of the first selected row, -1 if no row is selected.
    it says that only when row is selected. but clicking your check box does not select the whole row. so you need to listen for changes in the table itself. the best would be to write your own table model (extension of AbstractTableModel)
    this is how you should be able to get the change a your row where the change occurred
    public class YourClass implements TableModelListener{
    yourTable.getModel().addTableModelListener(this);
    public void tableChanged(TableModelEvent tme){
              int row = tme.getFirstRow();
              int col = tme.getColumn();
    //if you want your table model then do this
    TableModel tm = (TableModel)tme.getSource();
    }and now you should have the row a column where the change has occurred and that's it
    hope this will help
    v.v.

  • Checkbox selected : row not rendering

    I am not able to set colors for the row that has checked checkboxes. I want to set red color for the row having
    checked checkboxes and green for unchecked.
    table.getColumnModel().getColumn(3).setCellEditor(new CustomTableCellRenderer(new JCheckBox(),Name));
    table.getColumnModel().getColumn(3).setCellRenderer(new CustomTableCellRenderer3());
    setcellEditor:
    package moxaclient;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JCheckBox;
    import javax.swing.JTable;
    public class CustomTableCellRenderer extends DefaultCellEditor implements ItemListener{
    private static final long serialVersionUID = 1L;
    private JCheckBox checkBox;
    private JTable table1;
    private int row;
    private int column;
    Object abc="null";
    private String Name;
    Component comm=null;
    public CustomTableCellRenderer(JCheckBox checkBox,String name2) {
        super(checkBox);
        this.checkBox = checkBox;
        this.checkBox.addItemListener(this);
        this.Name=name2;  
    public Component getTableCellEditorComponent(JTable table, Object value,
            boolean isSelected,int row, int column)
        Component comp = super.getTableCellEditorComponent(table, value, isSelected, row, column);
        this.row = row;
        this.table1=table;
        this.column = column;
        checkBox.setSelected((Boolean)value);
        return super.getTableCellEditorComponent(table, value, isSelected,row, column);
    public void itemStateChanged(ItemEvent e)
       this.fireEditingStopped();
        //System.out.println("Item Changed " + row + " value is: " + checkBox.isSelected());
         //System.out.println("Item Changed " + column + " value is: " + checkBox.isSelected());
          String Sensor =(String) table1.getValueAt(row, 0);
          Double Value =(Double) table1.getValueAt(row, 1);
          String Date =(String) table1.getValueAt(row, 2);
          Boolean select=(Boolean) table1.getValueAt(row,3);
           if (Boolean.TRUE.equals(select))
            abc += Sensor+"\t"+Value+"\t"+Name+"\t"+Date+"\t";
            // table1.set Background(Color.black);
            //  checkBox.setBackground(Color.red);
              // comm.setBackground(Color.red);
        Clientthread ct=new Clientthread(abc);
    package moxaclient;
    import java.awt.Component;
    import java.util.EventObject;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JTable;
    import javax.swing.event.CellEditorListener;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    public class CustomTableCellRenderer3 extends DefaultTableCellRenderer {
    JTable table1=null;
    DefaultTableModel model;
        public CustomTableCellRenderer3() {
            // TODO Auto-generated constructor stub
        public CustomTableCellRenderer3(JTable table,DefaultTableModel model1) {
            this.table1=table;
            this.model=model1;
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
             Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
             Boolean last=(Boolean)model.getValueAt(row,3);
                       if(last)
                             //setcolor dosent work here
                    return null;
    }Edited by: 1000637 on Apr 17, 2013 5:29 AM

    I suggest first trying to get cell renderers to work as expected before going onto cell editors. See Using Custom Renderers in the Swing tutorial for basic information on how to use cell renderers. That said, subclassing DefaultTableCellRenderer won't do if you want to display a check box, because DTCR is a JLabel but you need to return a JCheckBox as cell renderer component. To get you startet, here is a simple demo for a custom JCheckBox based renderer:import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableCellRenderer;
    * Demonstrates how to create a custom boolean table cell renderer.
    public class BooleanRendererDemo {
       * Creates and displays a sample {@link JTable} with a customized boolean
       * table cell renderer.
      private void start() {
        // create a table with sample data
        final JTable jt = new JTable(new MyTableModel());
        // configure the renderer for boolean values
        jt.setDefaultRenderer(Boolean.class, new MyBooleanRenderer());
        // boiler plate code necessary for displaying a Swing GUI
        final JScrollPane jsp = new JScrollPane(jt);
        jsp.setPreferredSize(new Dimension(480, 320));
        final JFrame frame = new JFrame(BooleanRendererDemo.class.getName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(jsp);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main( String[] args ) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            (new BooleanRendererDemo()).start();
       * A customized table cell renderer for boolean values.
      private static final class MyBooleanRenderer implements TableCellRenderer {
        private final JCheckBox jcb;
        MyBooleanRenderer() {
          jcb = new JCheckBox();
          jcb.setHorizontalAlignment(JCheckBox.CENTER);
        public Component getTableCellRendererComponent(
                final JTable table,
                final Object value,
                final boolean isSelected,
                final boolean hasFocus,
                final int row,
                final int column
          final boolean state = value != null && ((Boolean) value).booleanValue();
          if (isSelected) {
            jcb.setForeground(table.getSelectionForeground());
            jcb.setBackground(table.getSelectionBackground());
          } else {
            jcb.setForeground(table.getForeground());
            // check if the renderer should display the last column
            // if so, use custom background colors depending on the cell value
            final boolean last = table.getModel().getColumnCount() == column + 1;
            if (last) {
              jcb.setBackground(state ? Color.GREEN : Color.RED);
            } else {
              jcb.setBackground(table.getBackground());
          jcb.setSelected(state);
          return jcb;
       * Dummy table model with nonsense sample data.
      private static final class MyTableModel extends AbstractTableModel {
        public Class getColumnClass( final int columnIndex ) {
          return columnIndex < 2 ? String.class : Boolean.class;
        public int getColumnCount() {
          return 4;
        public int getRowCount() {
          return 4;
        public Object getValueAt( final int rowIndex, final int columnIndex ) {
          if (columnIndex == 3) {
            return (rowIndex % 2) == 1 ? Boolean.TRUE : Boolean.FALSE;
          } else if (columnIndex == 2) {
            return (rowIndex % 2) == 0 ? Boolean.TRUE : Boolean.FALSE;
          } else {
            return "Dummy";
    }To customize cell editors, work through the JTable tutorial (and maybe take a quick look at DefaultCellEditor's OpenJDK sources).

  • Capturing events from a JCheckBox in a JTable cell

    I am trying to capture item state changed event from a JCheckbox in a JTable. When user selects checkbox I do insert in database and on deselect I do delete from database. The item state changed event is not firing correctly...can you please tell me what I am doing wrong. My JTable uses CustomModel which is used by many other apps. So I can not really modify CustomModel only to work with my JTable. Here is my code.
    public class MyClass extends JPanel
    .....some code to add panel, jscorollpane, etc.
    ResultSet res;
    GUI gui; //Custom Class to deal with different GUI layouts
    JTable myJTable = new JTable();
    GUI.CustomModel custModel;
    public void init()
         displayJTable();
    attachCheckBoxListeners();
    private void displayForms()
         res = //resultset from DB
    Vector cols = new Vector(10);
    cols.addElement(new Integer(1);
    gui.DisplayResultSetinTabel(res, myJtable, cols, null);
    custModel= (GUI.CustomModel) ((TableSorter) myJTable.getModel()).getModel();
    custModel.setEditableColumn(0, true);
    //Attach CheckBox Listener to all the checkbox in JTable
    private void attachCheckBoxListeners()
    for(int row = 0; row< myJTable.getRowCount(); row++)
    Object val = cm.getValueAt(row, 0);
    final JCheckBox jcb = (JCheckBox) gridForms.getCellEditor(row, 0).getTableCellEditorComponent(gridForms, val, true, row, 0);
    jcb.addItemListener( new java.awt.event.ItemListener() // Add Item Listener to trap events
    public void itemStateChanged(java.awt.event.ItemEvent event)
                   if(myJtable.getSelectedRow() == -1) // if no row is selected in table return
                        return;
                   try               
                   if (res.absolute(myJtable.getSelectedRow())+1))
         if(jcb.isSelected())
    saveData();();      
         else
    deleteData();
         catch(Exception e)
    System.out.println("ERROR ");
    } //end of AttachCheckBoxListeners ()
    private void SaveData() {}
    private void DeleteData() {}
    Okay....the problem is when JCheckBox state is changed (by user) from Selected to Deselected itemStateChanged() is fired and it does delete from database. then again itemStateChanged() called it detects Jcheckbox as selected and does inseret in database. On Jtable gui...that checkbox is still shown as desected.
    Please tell me what is going on here.....
    Thank you.

    In short - never listen to low-level events from editorComponents (low-level meaning everything below - and most of the time including - a editingStopped/editingCancelled of the cellEditor). Your problem belongs to the model realm - save if a cell value is changed - so solve it in the model realm by listening to event from the tableModel and trigger your business logic when you detect a change in that particular cell value.
    Greetings
    Jeanette

Maybe you are looking for

  • HP C6180 AIO Printer question

    I've gotten one of the above and love it's being aboe the print wirelessly. My issue is with the drivers. It seems that I can get but one brint quality and don't have the ability to opt for b&W or Color. Am I missing something in the settings and the

  • WebLogic_CMP_RDBMS 8.1 not installed?

    I'm getting the following odd error message on Weblogic 8.1 SP4 and SP5 when trying ejbc compile EJBs (upgrading WL6->WL8). Any idea what I'm doing wrong? [java] Persistence type 'WebLogic_CMP_RDBMS' with version '8.1' which is referenced in bean 'Ar

  • Some websites broken in all browsers after Lion upgrade

    After upgrading from 10.6.8, some websites are not loading properly in any web browser (latest versions of Safari, Chrome, Firefox, Opera). The pages appear as just text, with no images or css. This is happening in both 10.7.2 and 10.7.3. Example sit

  • Putting site problem. Please help.

    Hi - if anyone can help me it would be fantastic... I try to put my web site onto the remote site, which according to the split 'Remote Site/Local Files' view, it has done. But when I view the web address in the browser (safari), it is still the old

  • Filter for the current month

    Hi all, Our client wants to see the report for the current month whenever he opens the report. We have a field called date which shows the date when PO was created in the format of mm/yyyy and mmm yy(JAN 2004 or JAN 2007. How should I create a filter