Kevin
Kevin

Reputation: 6831

A question about correct way of using ListSelectionListener in a JTable

I am researching coding in Java to realize showing list of items and the user can select one of them by clicking on one item. The way that I chose is

1). I declared a DefaultTableModel type object and set the 7 column identifiers.

2). Then I just looped through my object list( which is of NodeList type), parsing each of them and turn it into an array and adding to the row of that table by calling:

model.addRow(myArray);

3). After that, I created a new JTable, and added my model to it and affix it with the GUI:

 table = new JTable(model);
 JScrollPane scrollpane = new JScrollPane(table);
 panel.add(scrollpane);

4). This is the step where I got stuck. By calling API of the JTable, I managed to get an instance of ListSelectionModel and attach a listener to it:

 table.getSelectionModel().addListSelectionListener
 (
    new ListSelectionListener() 
{
      public void valueChanged(ListSelectionEvent event)
       {
         int viewRow = table.getSelectedRow();

I could only manage to get here, that is the index of row, but what I am really trying to get is the value of those identifiers of this particular row. Suppose my identifiers are {"ID","HREF","Height","Width","Product","Type","Caption"}, I will be very grateful if you guys could help me on the next step on getting the value of any of these 7 identifiers of that selected row.

Thanks in advance!

Upvotes: 1

Views: 2062

Answers (1)

Jason Nichols
Jason Nichols

Reputation: 11733

If you just want a particular value from a row you can call:

table.getValueAt(row,col);

Where row is your viewRow, and col is the index of the above identifiers (so 0 would be ID, 2 would be Height, etc).

More details on the JTable JavaDocs

Upvotes: 3

Related Questions