Search code examples
javasqliteswingjtable

How do you take values from multiple row from a JTable and assign it to a variable?


I have a table(1 column, multiple rows) containing a list of Book names and a button. What is the right selection listener so that if I select MULTIPLE rows on the table, it will assign the values of the selected rows into a variable in concatenated format when I press the button?

example, if I select Item 1 through 7 from the table, it will be assigned to the variable as:

String selectedBooks = item1 + item2 + item3...;

i will use the values of the selectedBooks for a sqlite query later.

thank you for your help


Solution

  • Using table.getSelectedRows() will return the indices of selected rows. Then you use table.getValueAt(row,column) method to get the value from a specific cell.

    A tiny example:

    public class SelectedRowExample extends JFrame {
        public SelectedRowExample() {
            super("");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            DefaultTableModel model = new DefaultTableModel();
            model.addColumn("Column");
            model.addRow(new Object[] { "Hello" });
            model.addRow(new Object[] { "Stack" });
            model.addRow(new Object[] { "Overflow" });
            JTable table = new JTable(model);
            table.getSelectionModel().addListSelectionListener(e -> {
                if (e.getValueIsAdjusting()) {
                    StringBuilder sb = new StringBuilder();
                    for (int row : table.getSelectedRows()) {
                        sb.append(table.getValueAt(row, 0));
                    }
                    System.out.println(sb.toString());
                }
            });
    
            setLayout(new BorderLayout());
            add(table);
    
            setLocationByPlatform(true);
            pack();
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> new SelectedRowExample().setVisible(true));
        }
    }
    

    Selecting "Hello" prints: Hello

    Selecting "Hello" & "World" prints: HelloWorld

    Selecting all rows prints: HelloStackOverflow