I have developed a basic custom JTableModel as follows
public class CustomTableModel extends DefaultTableModel {
List<MyClass> data;
public CustomTableModel(List<MyClass> data) {
this.data = data;
}
public Class<?> getColumnClass(int columnIndex) {
return MyClass.class;
}
public MyClass getValueAt(int rowIndex, int columnIndex) {
return data.get(rowIndex);
}
// ...
}
I then use a basic custom JTableCellRenderer as follows
public class CustomTableCellRenderer extends JLabel implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
MyClass myClass = (MyClass)value;
lbl.setText(myClass.getString());
return this;
}
}
I also have a custom JPanel that displays various information as follows
public class MyPanel extends JPanel {
private MyClass myClass;
public MyPanel(MyClass myClass) {
// initialize components
}
public setMyClass(MyClass myClass) {
this.myClass = myClass;
updateFields();
}
private void updateFields() {
this.fieldString.setText(myClass == null ? "" : myClass.getString());
// ...
}
}
Finally, I use a table to list my data and the custom panel to display the details of the selected data.
public class JCustomFrame extends JFrame {
public JCustomFrame(List<MyClass> data) {
// ...
JTable table = new JTable(new CustomTableModel(data));
table.setDefaultRenderer(MyClass.class, new CustomTableCellRenderer());
}
}
What I am trying to accomplish is get the selected MyClass from the table regardless of sorting.
I tried ListSelectionListener but the methods do not return anything other than the selected indexes. Even if I have the index, if the table is sorted, my model is not so sophisticated and will return the wrong object.