Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Assuming the data is stored in a table or a 2D array, the method to obtain the value of a particular cell when a row is selected using ListSelectionModel is as follows:

  1. Get the index of the selected row using the ListSelectionEvent passed by the ListSelectionModel.

  2. Use this index to retrieve the corresponding row data from the table or 2D array.

  3. Get the value of the particular cell by accessing the desired column of the retrieved row data.

Here's some sample code that demonstrates this method:

// Assume tableData is a 2D array of data displayed in a JTable
// Assume listSelectionModel is the ListSelectionModel of the JTable

listSelectionModel.addListSelectionListener(new ListSelectionListener() {
    @Override
    public void valueChanged(ListSelectionEvent e) {
        if (!e.getValueIsAdjusting()) {
            int rowIndex = listSelectionModel.getMinSelectionIndex();
            Object[] rowData = tableData[rowIndex];
            Object cellValue = rowData[columnIndex]; // where columnIndex is the desired column index
            // Use the cell value as needed
        }
    }
});

Note that this code only handles single row selection. If multiple rows can be selected, the getMinSelectionIndex() method will return the index of the first selected row. To handle multiple row selection, you will need to iterate over all selected rows using getSelectedIndices() and retrieve their corresponding data.