title: Cast Object to JTable?
body: <p>I am trying to implement a ListSelectionListener for some of my JTables. Simply (at the moment) the ListSelectionListener is supposed to simply return the text of the cell that was selected.</p>
  
  <p>My program design has several JTables and I would like to have one ListSelectionListener work for them all. In the valueChanged event of the ListSelectionListener I thought it was possible to do something like:</p>
  
  <pre><code>private class SelectionHandler implements ListSelectionListener {
      public void valueChanged(ListSelectionEvent e)
      {
          JTable table = (JTable)e.getSource();                                                         
  
          String data = (String) table.getValueAt(table.getSelectedRow(), 0);
  
          // Print data
      }
  }
  </code></pre>
  
  <p>Behind the scenes I have used the following code to get the SelectionHandler working with the table in question:</p>
  
  <pre><code>fbTable.setCellSelectionEnabled(true);
  ListSelectionModel cellSM = fbTable.getSelectionModel();
  cellSM.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  cellSelectionModel.addListSelectionListener(selectionHandler);
  </code></pre>
  
  <p>When I run the program I get a ClassCastException error:</p>
  
  <pre><code>Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.DefaultListSelectionModel cannot be cast to javax.swing.JTable
          at cardboardfantasy.CardboardFantasyView$SelectionHandler.valueChanged(CardboardFantasyView.java:360)
  
  // This is the line in question: JTable table = (JTable)e.getSource();
  </code></pre>
  
  <p>Is there a way to do something like this? One solution I thought of was to compare the source of the event (e.getSource()) to all my JTables to see if they were equivalent (big if block) and then just calling .getValueAt inside that block but that would making the code in the future difficult if tables were to be added or removed.</p>