• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1359
  • Last Modified:

add check box and listener in table

I have a table and i want to add the checkbox and checkbox listener at the left hand side. But how can i add it?

thanks
0
Kennywen
Asked:
Kennywen
  • 15
  • 6
  • 5
  • +3
5 Solutions
 
mmuruganandamCommented:
u want to add the checkbox within the table

or

??


Regards,
Muruga
0
 
KennywenAuthor Commented:
yes, i want to add the checkbox within the table. (E.g. when user click on the particular checkbox then i will do something on the data for the specify row.)

thanks
0
 
mmuruganandamCommented:
See the below examples..

http://www.codeguru.com/java/articles/665.shtml
http://quicktable.org/jtable/quicktablemain.htm 


These might help you in having JCheckBox in a Cell of JTable.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
objectsCommented:
Just add Boolean's to a model something like:

public class MyTableModel extends DefaultTableModel
{
   public boolean isCellEditable(int row, int col)
   {
       return col==0;
   }

   public Class getColumnClass(int col)
   {
      return col==0 ? Boolean.class : super.getColumnClass(col);
   }

}
0
 
objectsCommented:
you'll also need to add a setValueAt() method
0
 
KennywenAuthor Commented:
how about the item listener?
0
 
mmuruganandamCommented:
Add the checkbox component to the cell as given in the example
and add your listener to that.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
0
 
objectsCommented:
instead of an itemlistener you would use a TableModelListener to listener for changes to table data.
0
 
KennywenAuthor Commented:
currently i'm using boolean datatype to make the checkbox and i have a checkbox for the table header too.

Checkbox header is create by:
JTableHeader header = table.getTableHeader();  
header.addMouseListener(new ColumnHeaderListener());
MyItemListener myItemListener = new MyItemListener();
Enumeration enumeration = table.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
      TableColumn aColumn = (TableColumn)enumeration.nextElement();
      aColumn.setHeaderRenderer(new CheckBoxHeader(myItemListener));
      break;
}

when the user click on the checkbox on the header then i will set all the checkbox in the table to become checked. but when the user uncheck all the checkbox on the table then how can i uncheck the checkbox on the table header.

thanks
0
 
objectsCommented:
you need to define a header cell editor.
0
 
KennywenAuthor Commented:
i think i can use :
table.getModel().addTableModelListener(new MyTableModelListener(table));
0
 
rama_krishna580Commented:
check this code..it will help you..

JTable table = new JTable();
   
    // Add data
   
    // Create text field and add action
    JTextField textField = new JTextField();
    textField.setAction(new UpdateAnchorAction(table));
   
    // Add selection listener to table
    SelectionListener listener = new SelectionListener(table, textField);
    table.getSelectionModel().addListSelectionListener(listener);
    table.getColumnModel().getSelectionModel()
        .addListSelectionListener(listener);
   
    // Add value changed listener to table
    table.getModel().addTableModelListener(new MyTableModelListener(table, textField));
   
    // Create a frame and add both components to the frame
    JFrame frame = new JFrame();
    frame.getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
    frame.getContentPane().add(textField, BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
   
    public class SelectionListener implements ListSelectionListener {
        JTable table;
        JTextField textField;
   
        // It is necessary to keep the table since it is not possible
        // to determine the table from the event's source
        SelectionListener(JTable table, JTextField textField) {
            this.table = table;
            this.textField = textField;
        }
   
        // Update the text field whenever the anchor cell changes
        public void valueChanged(ListSelectionEvent e) {
            int rowIndex = table.getSelectionModel().getAnchorSelectionIndex();
            int vColIndex = table.getColumnModel().getSelectionModel()
                .getAnchorSelectionIndex();
   
            // Get the value and set the text field
            textField.setText((String)table.getValueAt(rowIndex, vColIndex));
        }
    }
   
    public class MyTableModelListener implements TableModelListener {
        JTable table;
        JTextField textField;
   
        // It is necessary to keep the table since it is not possible
        // to determine the table from the event's source
        MyTableModelListener(JTable table, JTextField textField) {
            this.table = table;
            this.textField = textField;
        }
   
        // Update the text field whenever the value in the anchor cell changes
        public void tableChanged(TableModelEvent e) {
            // Get anchor cell location
            int rAnchor = table.getSelectionModel().getAnchorSelectionIndex();
            int vcAnchor = table.getColumnModel().getSelectionModel()
                .getAnchorSelectionIndex();
   
            // This method is defined in
            // e915 Converting a Column Index Between the View and Model in a JTable Component
            int mcAnchor = toModel(table, vcAnchor);
   
            // Get affected rows and columns
            int firstRow = e.getFirstRow();
            int lastRow = e.getLastRow();
            int mColIndex = e.getColumn();
   
            if (firstRow != TableModelEvent.HEADER_ROW
                    && rAnchor >= firstRow
                    && rAnchor <= lastRow
                    && (mColIndex == TableModelEvent.ALL_COLUMNS
                        || mColIndex == mcAnchor)) {
                // Set the text field with the new value
                textField.setText((String)table.getValueAt(rAnchor, vcAnchor));
            }
        }
    }
   
    public class UpdateAnchorAction extends AbstractAction {
        JTable table;
        UpdateAnchorAction(JTable table) {
            super("Set Anchor");
            this.table = table;
        }
   
        // Update the value in the anchor cell whenever the text field changes
        public void actionPerformed(ActionEvent evt) {
            JTextField textField = (JTextField)evt.getSource();
   
            // Get anchor cell location
            int rAnchor = table.getSelectionModel().getAnchorSelectionIndex();
            int vcAnchor = table.getColumnModel().getSelectionModel()
                .getAnchorSelectionIndex();
   
            table.setValueAt(textField.getText(), rAnchor, vcAnchor);
        }
    }


R.k
0
 
rama_krishna580Commented:
The trick is to listen to the model of the table.

Table models fire events in the TableModelListener interface.

If you implement this interface, you can add a listener to the table model as follows:

  tableName.getModel().addTableModelListener(new MyTableModelListener());

all the best

R.K
0
 
KennywenAuthor Commented:
my problem on the tableName.getModel().addTableModelListener(new MyTableModelListener()); is when i call customCheckbox.setSelected(false); the checkbox will not become uncheck but when i minimize and then maximize the window the checkbox will become uncheck. why?

JTableHeader header = table.getTableHeader();  
header.addMouseListener(new ColumnHeaderListener());
MyItemListener myItemListener = new MyItemListener();
table.getModel().addTableModelListener(new MyTableModelListener(table));
Enumeration enumeration = table.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
      customCheckbox = new CheckBoxHeader(myItemListener);
      TableColumn aColumn = (TableColumn)enumeration.nextElement();
      aColumn.setHeaderRenderer(customCheckbox);
      break;
}

thanks
0
 
KennywenAuthor Commented:
do i need to refresh the table?
0
 
mmuruganandamCommented:
For table data change..

((AbstractTableModel)table.getModel()).fireTableDataChanged();


For structure change of table

((AbstractTableModel)table.getModel()).fireTableStructureChanged() ;
0
 
KennywenAuthor Commented:
just wonder why the customCheckbox.setSelected(false); will not set the checkbox to false.

public class CheckBoxHeader extends JCheckBox
0
 
KennywenAuthor Commented:
can i just refresh the table header?

thanks
0
 
mmuruganandamCommented:
You can't do that...
0
 
KennywenAuthor Commented:
can anyone tell me why the customCheckbox.setSelected(false); will not uncheck the checkbox?

thanks
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Try calling the updateUI () method on the table.
0
 
KennywenAuthor Commented:
>> customCheckbox.updateUI();

still the same.
0
 
KennywenAuthor Commented:
the checkbox will become uncheck when i click on the table header.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
I said: >> on the table.

table.updateUI () ;
0
 
KennywenAuthor Commented:
how can i call the click table header function in my program?

thanks
0
 
KennywenAuthor Commented:
Sorry,
>> table.updateUI () ;

also the same.
0
 
KennywenAuthor Commented:
actually the checkbox is unchecked when i call customCheckbox.setSelected(false); the only problem is the tick graphic still in the checkbox. after i call customCheckbox.setSelected(false); the checkbox will become checked when i try to click on the checkbox. the only problem is the tick graphic....
0
 
zzynxSoftware engineerCommented:
>> I have a table and i want to add the checkbox and checkbox listener at the left hand side. But how can i add it?

I created a demo app for you from scratch. It consists of three files

1) MyObject.java  (the object that contains the info of your table rows)

public class MyObject {
   
    private boolean bool = false; // default value
    private String field1 = ""; // default value
    private int field2 = 0; // default value

    public MyObject() {
    }

    public String getField1() { return field1; }
    public int getField2() { return field2; }
    public void setField1(String f1) { field1 = f1; }
    public void setField2(int f2) { field2 = f2; }
    public boolean getBool() { return bool; }
    public void setBool(boolean b) { bool = b; }
}

2) MyTableModel.java (the table model to use for your table):

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

public class MyTableModel extends DefaultTableModel {
   
    List data; // a list of MyObject's
   
    final String[] columnNames = { "my check box", "field 1", "field 2" };
   
    public MyTableModel(List d) {
        this.data = d;
    }

   public boolean isCellEditable(int row, int col) {
     return col==0;
   }

   public Class getColumnClass(int col) {
      return col==0 ? Boolean.class : super.getColumnClass(col);
   }
   
   public int getRowCount() {
       return data==null ? 0 : data.size();
   }
   
    public int getColumnCount() {
        return columnNames.length;
    }
   
    public Object getValueAt(int row, int col) {
        if ( row < 0 || row >= data.size() ) return null;
        MyObject myObj = (MyObject) data.get(row);
        if (col==0)
            return new Boolean(myObj.getBool());
        else if (col==1)
            return myObj.getField1();
        else if (col==2)
            return new Integer(myObj.getField2());
        else return null;
    }

    public void setValueAt(Object value, int row, int col) {
        if ( row < 0 || row >= data.size() || col!=0 ) return;
        // only col=0 is editable (in this example)
        MyObject myObj = (MyObject) data.get(row);
        myObj.setBool( ((Boolean)value).booleanValue() );
        if ( ((Boolean)value).booleanValue() )
            myObj.setField2(1000);
        else
            myObj.setField2(900);
        fireTableCellUpdated(row, col);
        fireTableCellUpdated(row, 2); // to see the field2 changes
    }
   
    public String getColumnName(int col) {
        return columnNames[col];
    }
}

3) TableDemo (the main app that shows how to use the above):

import java.util.*;
import javax.swing.*;

public class TableDemo extends javax.swing.JFrame {

    private JScrollPane jScrollPane1;
    private JTable theTable;
   
    public TableDemo() {
        initComponents();
        initTable();
    }
   
    private void initTable() {
        MyTableModel model = new MyTableModel(getTableData());
        theTable.setModel(model);
    }
   
    private List getTableData() {
        // For this example we generate the data (hardcoded)
        List data = new ArrayList();
        MyObject obj = new MyObject();
        obj.setField1("Field1 entry");
        data.add( obj );
        obj = new MyObject();
        obj.setField1("Field1 another entry");
        obj.setField2(15);
        data.add( obj );
        obj = new MyObject();
        obj.setField1("Field1 yet another");
        obj.setField2(45);
        data.add( obj );
        return data;
    }
   
    private void initComponents() {
        jScrollPane1 = new javax.swing.JScrollPane();
        theTable = new javax.swing.JTable();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

        jScrollPane1.setViewportView(theTable);

        getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);

        pack();
    }
   
    private void exitForm(java.awt.event.WindowEvent evt) {
        System.exit(0);
    }
   
    public static void main(String args[]) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (Exception e) {
            System.exit(0);
        }
       
        new TableDemo().show();
    }
}

When you run this demo you will be able to check/uncheck the check boxes in the 1st column.
When you check them, you'll see that field2 becomes 1000. When you uncheck field2 becomes 900.
(Weird behaviour but hey, it's to demo ;)
0
 
objectsCommented:
That TableModel looks familiar :)
0
 
KennywenAuthor Commented:
i get my solution by repaint the panel........
0
 
objectsCommented:
:)
0
 
zzynxSoftware engineerCommented:
Thanks for accepting
0
 
rama_krishna580Commented:
best of luck..

R.K

0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 15
  • 6
  • 5
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now