Akhilesh Mohare
Akhilesh Mohare

Reputation: 45

Select Value of Checkbox JTable on button click

I have a JTable in which the last column is Checkbox(multiple select). I want to get the values of the rows selected on a particular button click. Only the values which are checked are needed. Any idea regarding this?

Object[] columnNamesTest = {"Request No","Assigned To","Copy Data","Updated Req Number"};
        Object[][] rowDataTest = {
            {"111111", "ABC",false,""},
            {"222222", "XYZ", true,"999999"},
            {"333333", "LMN",true,"444444"},
            {"444444", "PQR", false,"555555"}
        };
     DefaultTableModel model = new DefaultTableModel(rowDataTest, columnNamesTest);
     JTable table = new JTable(model){
         private static final long serialVersionUID = 1L;
          @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Boolean.class;
                    default:
                        return String.class;
                }
            }
             @Override
               public boolean isCellEditable(int row, int column) {
                   //Only the third column
                   return column == 2;
               }

     }; 

    table.setPreferredScrollableViewportSize(table.getPreferredSize());
    JScrollPane scrollPane = new JScrollPane(table);
    scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
    container.add(scrollPane);

Upvotes: 1

Views: 1286

Answers (1)

Braj
Braj

Reputation: 46841

I want to get the values of the rows selected on a particular button click.Only the values which are checked are needed.

Simply check the value of third column and get it the desired value from DefaultTableModel.

sample code:

JButton button = new JButton("Show selcted records");
button.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        for (int i = 0; i < model.getRowCount(); i++) {
            Boolean value = (Boolean) model.getValueAt(i, 2);// check state
            if (value) {
                System.out.println(model.getValueAt(i, 1));// second column value
            }
        }
    }
});

Upvotes: 1

Related Questions