JTable - Checkbox add action listener
Asked Answered
H

2

5

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.

Humanity answered 28/3, 2014 at 10:43 Comment(5)
can i get sample or reference link for it.Humanity
I want to add action listener for the check box no, you don't :-) Still not learned how to use editors/tables?Bysshe
@Bysshe do u saying I cant add action listener. What is the best way to achieve this then.?Humanity
read a basic tutorial on how to use tables (f.i. the one referenced in swing tag wiki above) - as you were already advised the last time you swamped the site with your Swing questions ;-) You have to learn the basic concepts yourself, nothing anybody here can do about that. And again, you didn't explain what exactly you are trying to achieve ... voting to close besides the -1Bysshe
"do u saying I cant add action listener." - Quote from Concepts: Editors and Renderers: "Before you go on to the next few tasks, you need to understand how tables draw their cells. You might expect each cell in a table to be a component. However, for performance reasons, Swing tables are implemented differently. Instead, a single cell renderer is generally used to draw all of the cells that contain the same type of data."Pegu
D
12

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.

Delfeena answered 28/3, 2014 at 11:19 Comment(0)
C
1

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

Carburet answered 28/3, 2023 at 7:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.