1

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);
tashuhka
  • 5,028
  • 4
  • 45
  • 64
Akhilesh Mohare
  • 45
  • 2
  • 13
  • Maybe you can add an handler when a checkbox is selected and for each selected item you can create a list that you can display – Ko2r Jul 31 '14 at 11:34

1 Answers1

1

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
            }
        }
    }
});
Braj
  • 46,415
  • 5
  • 60
  • 76
  • Hey Thanks,that worked.One more question i wanted to ask.Once i perform some action (updating some value in db from which the data in Jtable is fetched).how can i refresh the page to show the updated table – Akhilesh Mohare Jul 31 '14 at 11:54
  • This [post](http://stackoverflow.com/questions/3179136/jtable-how-to-refresh-table-model-after-insert-delete-or-update-the-data) will answer your question. – Braj Jul 31 '14 at 12:22