Cast Object to JTable?
        Posted  
        
            by Chris
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Chris
        
        
        
        Published on 2010-05-18T19:32:30Z
        Indexed on 
            2010/05/18
            19:40 UTC
        
        
        Read the original article
        Hit count: 285
        
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.
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:
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
    }
}
But when I do this I a ClassCastException error. 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.
© Stack Overflow or respective owner