Question

I've created a simple JTable with check box like below:

DefaultTableModel model = new DefaultTableModel();
jTable1.setModel(model);

model.addColumn("No:", no1);
model.addColumn("Remark", remark1);
model.addColumn("Color", colors1);
model.addColumn("Done");

TableColumn col1 = jTable1.getColumnModel().getColumn(0);
col1.setPreferredWidth(1);

TableColumn col4 = jTable1.getColumnModel().getColumn(3);
col4.setCellEditor(jTable1.getDefaultEditor(Boolean.class));
col4.setCellRenderer(jTable1.getDefaultRenderer(Boolean.class));
col4.setPreferredWidth(50);

jTable1.setShowGrid(true);
jTable1.setGridColor(Color.BLACK);
jTable1.setAutoCreateRowSorter(true); 

It's working fine but how to do if I want to add action listener for the check box. For an example, when my check box is checked I need to pop up a confirmation message.

Was it helpful?

Solution

For an example, when my check box is checked I need to pop up a confirmation message.

You don't need to add an ActionListener to the renderers/editors but you need to listen to table model data changes. Take a look to Listening for Data Changes section of How to Use Tables tutorial:

  • Add a new TableModelListener to your TableModel
  • Validate if the updated cell value is a Boolean and its value is true.
  • Ask the user to confirm the update. If s/he doesn't then set the cell's value back to false.
  • See TableModelEvent API as well.

Edit

Note in this case as you're working with booleans then there's 2 possible values to do the check. However for input validation in other cases the described procedure won't work simply because the listener will be notified when the change already happened and you won't be able to set the value back just because it won't be there any longer.

Take a look to @kleopatra's answer to this question: JTable Input Verifier. As stated there a better approach is providing a custom CellEditor and do the validation in stopCellEditing() method implementation. Just as a suggestion I'd use a DefaultCellEditor that takes a JCheckBox as parameter and override the aforementioned method.

OTHER TIPS

You have to add Item Listener to add an action listener in the checkbox. Here is a simple example of a restaurant billing system:

package swingDemo;

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

public class RestaurantOrderingBilling extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;
    
    JButton b; 
    JLabel l;
    public RestaurantOrderingBilling() {
        Object[] columnNames = {"Select", "Item Names", "Price"};
        Object[][] data = {
                {false, "Burger", new Double(120.0)},   
                {true, "Chowmin", new Double(180.0)},
                {false, "Pizza", new Double(200.0)},
        };

        DefaultTableModel model = new DefaultTableModel(data, columnNames);

        table = new JTable(model) {
            private static final long serialVersionUID = 1L;

            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return Boolean.class;
                    case 1:
                        return String.class;
                    default:
                        return Double.class;    
                }
            }
        };
        
        // Add an ItemListener to the checkboxes in the table
        TableColumnModel columnModel = table.getColumnModel();
        TableColumn column = columnModel.getColumn(0);
        column.setCellEditor(table.getDefaultEditor(Boolean.class));
        column.setCellRenderer(table.getDefaultRenderer(Boolean.class));
        JCheckBox checkBox = new JCheckBox();
        checkBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                int row = table.getSelectedRow();
                int column = table.getSelectedColumn();
                Boolean selected = (Boolean) model.getValueAt(row, column);
                System.out.println("Checkbox in row " + row + " is " + (selected ? "not selected" : "selected") +" Price: "+data[row][2]);
            }
        });
        column.setCellEditor(new DefaultCellEditor(checkBox));
        
        l = new JLabel("");
        // define the order button
        b = new JButton("Order Items");
        
        b.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                     // Find the total price    
                    double totalPrice = 0.0;
                    int numRows = model.getRowCount();
                    for (int i = 0; i < numRows; i++) {
                        Boolean selected = (Boolean) model.getValueAt(i, 0);
                        if (selected) {
                            Double price = (Double) model.getValueAt(i, 2);
                            totalPrice += price;
                        }
                    }
                    System.out.println("Total Price: " + totalPrice);
                    l.setText("Total Price: "+totalPrice);
                }
                
    });
       
        
        table.setShowGrid(false);
        
        add(table);
        add(b);
        add(l);

        setLayout(new FlowLayout());
        setResizable(false);
        setVisible(true);
        setSize(400, 400);
    }

    public static void main(String args[]) {
        new RestaurantOrderingBilling();
    }
}



GUI Output looks like this:

GUI Output

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top